Reputation: 579
Trying number validation with space in it. but its not working for me.
if(!user_phone.match(/[^0-9\s]/))
{
$('#user_phone').css({"border":"1px solid red"});
return false;
}
What will be the regex expression i have to use?
Upvotes: 2
Views: 5740
Reputation: 6047
Here is an example how to be done:jsfiddle
Here is the actual code:
$('button').on('click', function(e){
user_phone = $('#user_phone').val();
$('#user_phone').css({"border":"1px solid #ccc"});
if(!user_phone.match(/^\d[\d\s]+\d$/))
{
$('#user_phone').css({"border":"1px solid red"});
}
})
The check means:
Also never forget to reset the state, because on later stage you will always get red background if you enter even 1 wrong phone number
Upvotes: 1
Reputation: 107287
You are using a negated character class which match everything except number and whitespace, you need to put the anchor ^
out of character class:
/^[0-9\s]/
Also note that if you want to match more than one character you can use modifier +
to match one or more combinations of number and whitespace :
/^[0-9\s]+/
And note that \s
will match all the whitespaces contain tab and ..., if you want to just match the space you need to use space ^[0-9 ]+
.And if you want to use this regex in a multi-line text you need to use flag m
which makes the regex engine match the anchor ^
from start of each line.
Upvotes: 2