0

我对 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 多个字段,所以任何重大变化都是痛苦的。有什么帮助吗?

4

1 回答 1

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;
    }

希望这能满足您的需求

于 2013-04-04T06:49:03.613 回答