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
2 Answers
Reset to default 13You 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