Mr.Happy
Mr.Happy

Reputation: 2647

Validation issue with condition

I am new with JavaScript validation and learning I am trying to validate form but I am getting issue with condition.

In my form I have one field which is name and one submit button.

What I am trying is:

If user click to to submit button and text box is empty give alert('Please enter your First Name.')

Then If user entered value which is not allowed by regex give alert('Please enter only letters no special character allowed.');

but I am getting first alert every time. Whats wrong i don't understand.

My Code:

jQuery('#send').click(function () {

    var reg_first_name = /^[A-Za-z ]{3,20}$/;

    var first_name = jQuery('#sa_first_name').val();

    if(first_name.length > 0){
        alert('Please enter your First Name.');
        document.getElementById("sa_first_name").focus();
        return false;
    }
    if (!reg_first_name.test(first_name)) {
        alert('Please enter only letters no special character allowed.');
        document.getElementById("sa_first_name").focus();
        return false;
    }

    return false;
});

Can you guide me?

Upvotes: 2

Views: 64

Answers (2)

tliokos
tliokos

Reputation: 3636

In case the user enters a name the first_name.length > 0 will always be true.

You can check it like

if($.trim(first_name) == '')

to also avoid only spaces

Upvotes: 3

s4m0k
s4m0k

Reputation: 568

condition is wrong

if(first_name.length > 0){

if you want to check that first_name must have value then your condition must be

if(first_name.trim().length == 0){

Upvotes: 2

Related Questions