我遇到了jQuery验证问题。
HTML:
<form action="#" name="validate" onsubmit="return validateRegistration();">
<input type="text" id="username" value="Username" />
<input type="text" id="email" value="Email" />
<input type="text" id="phone" value="Phone" />
</form>
function validateRegistration() {
var username = $('#username').val();
var email = $('#email').val();
var phone = $('#phone').val();
if(username=='' || username == 'Username'){
$('#username').after('<span class="error">Enter a username</span>');
}
if(email=='' || email == 'Email'){
$('#email').after('<span class="error">Please enter a valid email address</span>');
}
if(phone=='' || phone == 'Phone'){
$('#phone').after('<span class="error">This field is required.</span>');
return false;
}
}
当表单中没有值时,验证有效。如果我只填写电话字段,则表单会以return true
提交。我无法将return false
放在所有字段中,因为所有验证错误都应该一次可见。我给出的代码简短而原始。我有30多个领域,所以任何重大变化都是痛苦的。有什么帮助吗?
答案 0 :(得分:1)
function validateRegistration() {
var notError = true;
var username = $('#username').val();
var email = $('#email').val();
var phone = $('#phone').val();
if(username=='' || username == 'Username'){
$('#username').after('<span class="error">Enter a username</span>');
notError = false;
}
if(email=='' || email == 'Email'){
$('#email').after('<span class="error">Please enter a valid email address</span>');
notError = false;
}
if(phone=='' || phone == 'Phone'){
$('#phone').after('<span class="error">This field is required.</span>');
notError = false;
}
return notError;
}
希望这能满足您的需求