最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Regex to allow hypen & number only - Stack Overflow

programmeradmin8浏览0评论

I am using the RegEx ^[0-9]+$" to allow only digits. I want to allow hyphens - & spaces also.

Can any one help me to modify the RegEx to a proper one?

I was using following JS code to achieve the same, but in this way if the user is copying & pasting the text then the key press is not getting accounted.

//Allowed characters are : 8 = Back space,
//9 = Horizontal tab, 27 = esc, 127 = Delete,
//13 = Enter digits = 48 to 57, 45 = hypen

$('#PostalCode').keypress(function (e) {
    var key = (e.keyCode ? e.keyCode : e.which);
    return (key == 8 || key == 9 || key == 127 || key == 27 || key == 13 || key == 45 || (key >= 48 && key <= 57));
});

I am using the RegEx ^[0-9]+$" to allow only digits. I want to allow hyphens - & spaces also.

Can any one help me to modify the RegEx to a proper one?

I was using following JS code to achieve the same, but in this way if the user is copying & pasting the text then the key press is not getting accounted.

//Allowed characters are : 8 = Back space,
//9 = Horizontal tab, 27 = esc, 127 = Delete,
//13 = Enter digits = 48 to 57, 45 = hypen

$('#PostalCode').keypress(function (e) {
    var key = (e.keyCode ? e.keyCode : e.which);
    return (key == 8 || key == 9 || key == 127 || key == 27 || key == 13 || key == 45 || (key >= 48 && key <= 57));
});
Share Improve this question edited Aug 10, 2012 at 10:46 Adi 5,1796 gold badges35 silver badges48 bronze badges asked Aug 10, 2012 at 10:36 BikiBiki 2,5888 gold badges39 silver badges53 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 13

You can add a - and space in the character class like so:

^[0-9 -]+$

Be sure to put the - either in the back or front (as it won't be mistaken for a range, then), or escape it:

^[0-9 \-]+$

You could also use \d instead of 0-9, as they're equivalent:

^[\d -]+$

use ^[\d-\s]+$ to allow hyphens also

发布评论

评论列表(0)

  1. 暂无评论