Manish Rane
Manish Rane

Reputation: 579

Only Number with space validation in javascript regex

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

Answers (4)

Nik Chankov
Nik Chankov

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:

  1. if the match is not true, colour the input's border red.
  2. In the match is says: if the value is starting with digit and ending with digit (because starting/ending with space doesn't make any sense) and in between there are only numbers and spaces (more than one) than one, then it's a true (but because of the not (!), then it will check for invalid phone numbers.

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

Kasravnd
Kasravnd

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

Mayur Koshti
Mayur Koshti

Reputation: 1852

You can also use this:

/^[\d\s]+$/

Upvotes: 1

Ranjana
Ranjana

Reputation: 815

Try using this regex /^[0-9 ]+$/ or [0-9 ]+
Hope this helps.

Upvotes: 4

Related Questions