Sree Sree - 17 days ago 5
Javascript Question

jQuery form validation not working in several if statements

I have a problem with jQuery validation.

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


Validation works when the form has no values in it. And if I fill only phone fields, the form submits with
return true
. I can't put
return false
in all fields, since all the validation errors should be visible at a time. The code I have given is short and original. I have more than 30 fields, so any major variation is a pain. Any help?

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

Hope this will satisfy your need

Comments