Reputation: 2647
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
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
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