admin管理员组

文章数量:1357702

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?

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?

Share Improve this question asked Oct 16, 2015 at 8:02 Manish RaneManish Rane 5792 gold badges5 silver badges16 bronze badges 2
  • Where do you want Space at? – divy3993 Commented Oct 16, 2015 at 8:05
  • "not working" isn't helpful. Does it match more than you want? Less than you want? Which cases it is failing? Does it shut down your puter? Does it produce a cow when run? What is it doing that you don't want it to do, or what is it not doing that you do want it to do? What values have you tested it with? – Amadan Commented Oct 16, 2015 at 8:05
Add a ment  | 

4 Answers 4

Reset to default 4

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

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 binations 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.

You can also use this:

/^[\d\s]+$/

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

本文标签: jqueryOnly Number with space validation in javascript regexStack Overflow