当我检查用户名并且一切顺利时,id为user_error的范围变空,但是当我检查电子邮件并且它说跨区email_error不为空时,它的方式不一样。为什么会这样?
<form name="field" method="post" id="form">
<label for="username">Username:</label><br>
<input name="username" id="username" type="text"/>
<span id="user_error"></span><br><br>
<label for="email">Email:</label><br>
<input name="email" id="email" type="text"/>
<span id="email_error"></span><br><br>
<input name="submit" type="button" value="Register" id="submit"/><br>
</form>
的jQuery
$(document).ready(function() {
$("#username").blur(validateUser);
$("#email").blur(validateEmail);
$("#submit").click(submitForm);
function validateUser() {
var user = $("#username").val();
var user_regex = /^([^\s])*$/;
if($("#username").val().length == 0)
$("#user_error").html("Insert username");
else if($("#username").val().length > 14)
$("#user_error").html("Username too long");
else if($("#username").val().length < 6)
$("#user_error").html("Username too short");
else if (user_regex.test(user) == false)
$("#user_error").html("Username no whitespaces");
else
$("#user_error").html("");
}
function validateEmail() {
var email = $("#email").val();
var email_regex = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
if($("#email").val().length == 0)
$("#email_error").html("Insert email");
else if (email_regex.test(email) == false)
$("#email_error").html("Email not valid");
else
$("#email_error").html("");
}
function submitForm() {
var username = $("#username").val();
var email = $("#email").val();
//if ($("#user_error").text().length){
//alert ('ERROR!')
//}
//else {
// alert ('OK!')
//}
if ($("#email_error").text().length){
alert ('ERROR!')
else
alert ('OK!')
}
});
答案 0 :(得分:0)
尝试:
if ($("#email_error").text().length == 0)
答案 1 :(得分:0)
也许是因为您要验证blur
上的字段,而不是submit
上的字段?加上这个:
function submitForm() {
$('#username,#email').trigger('blur');