3

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));
});
4

2 回答 2

9

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 -]+$
于 2012-08-10T10:39:49.757 回答
1

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

于 2012-08-10T10:38:23.667 回答