Sha*_*aoz 1 javascript validation
我有一个登录表单,但我想检查字段是否为空,然后不提交.我在提交时"返回false",但浏览器仍会加载新页面.我怎么能阻止它?
JS:
var username = document.getElementById('usernameField');
var password = document.getElementById('passwordField');
var loginBtn = document.getElementById('loginBtn');
var infoBox = document.getElementById('formInfo');
var isEmpty = /^\s*$/;
var addEventTo = function(id, type, fn, capture) {
if (document.addEventListener) {
id.addEventListener(type, fn, capture);
} else {
id.attachEvent('on'+type, fn);
}
};
function checkIfAllEmpty() {
var loginForm = document.getElementById('loginform'),
allInputs = loginForm.getElementsByTagName('input'),
max = allInputs.length,
i;
for (i = 0; i < max; i++) {
if (allInputs[i].type !== 'submit') {
if (allInputs[i].match(isEmpty)) {
infoBox.innerHTML = 'All your fields are empty';
return false;
}
}
}
}
//addEventTo(loginBtn, 'click', checkIfAllEmpty, false);
if (document.addEventListener) {
loginBtn.addEventListener('submit', checkIfAllEmpty, false);
} else {
loginBtn.attachEvent('onsubmit', checkIfAllEmpty);
}
Run Code Online (Sandbox Code Playgroud)
HTML:
<p id="formInfo"></p>
<form id="loginForm" method="post" action="#">
<fieldset id="loginFieldset">
<legend>Sign in</legend>
<ol>
<li>
<label for="usernameField">Username</label><input type="text" placeholder="Enter username" id="usernameField" />
<span>Please type in your username</span>
</li>
<li>
<label for="passwordField">Password</label><input type="password" placeholder="Enter password" id="passwordField" />
<span>Please type your password</span>
</li>
<li>
<input type="submit" value="Sign in" id="loginBtn" />
</li>
</ol>
</fieldset>
</form>
Run Code Online (Sandbox Code Playgroud)
非常感谢
小智 7
如果可以使用html5(适用于较新版本的Safari,Chrome,Firefox,Opera> 11.00但不像往常一样使用IE),您可以在输入字段中添加所需的标记.
<p id="formInfo"></p>
<form id="loginForm" method="post" action="#">
<fieldset id="loginFieldset">
<legend>Sign in</legend>
<ol>
<li>
<label for="usernameField">Username</label>
<input type="text" placeholder="Enter username" id="usernameField" required />
<span>Please type in your username</span>
</li>
<li>
<label for="passwordField">Password</label>
<input type="password" placeholder="Enter password" id="passwordField" required />
<span>Please type your password</span>
</li>
<li>
<input type="submit" value="Sign in" id="loginBtn" />
</li>
</ol>
</fieldset>
Run Code Online (Sandbox Code Playgroud)
看起来onsubmit的事件监听器没有被正确添加,无论如何最简单的方法是在你的表单中添加onsubmit ="return someValidationFuncThatReturnTrueOrFalse()":
<form id="loginForm" method="post" action="#" onsubmit="return validate()">
Run Code Online (Sandbox Code Playgroud)
我可以问你为什么在你的js代码上使用这种方法吗?如果你的表格是静态的,它可以很容易地完成......
function validate() {
if (document.getElementById("usernameField").value == "" && document.getElementById("usernameField").value == "") {
alert("all fields are empty");
return false;
} else {
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
或类似的东西 ...
| 归档时间: |
|
| 查看次数: |
19981 次 |
| 最近记录: |