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
4 Answers
Reset to default 4Try 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:
- if the match is not true, colour the input's border red.
- 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
版权声明:本文标题:jquery - Only Number with space validation in javascript regex - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744009300a2575269.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论