我正在尝试制作一个简单的注册表单,确保在提交前已正确输入用户名和密码。这是我的表格:
<form id="register" name="register" action="" method="POST" onsubmit="return validate_account_creation(this)">
<label> Username
<input type="text" name="username" />
</label>
<label> Password
<input type="text" name="password" />
</label>
<input type="submit" name="submit" value="Submit" class="button"/>
</form>
这是我的javascript函数:
function validate_username(username) {
var regex = /[a-zA-Z0-9\-\_]{5,15}/g;
var str = username;
if (!regex.test(str)) {
alert("Your username must be between 5 and 15 characters in length");
register.username.focus();
return false;
}
}
function validate_password(password) {
regex = /[a-zA-Z]{5,}[0-9]{1,}/g;
str = password;
if (!regex.test(str)) {
alert("Your password must be at least 6 characters in length and must contain at least 1 number");
register.password.focus();
return false;
}
}
//Validate register form
function validate_account_creation(form) {
return validate_username(form.username.value);
return validate_password(form.password.value);
return true;
}
用户名功能正常工作,每次验证一次。但是,如果用户名正确,则表单提交。第二个功能永远不会激活。如果第一个函数没有返回任何内容,那么不应该调用第二个函数并验证第二个字段吗?
答案 0 :(得分:2)
它是退货声明。 return
中止函数的其余部分并返回结果,因此您的验证应如下所示:
<强>的Javascript 强>
function validate_account_creation(form) {
var username = validate_username(form.username.value);
var password = validate_password(form.password.value);
return username && password; // if both are true, submit form
}