Regex in javascript that allows backspace
5 answers
You can use [\b]
backspace to match. So, just add it to your character class: -
var numericReg = /^[a-zA-Z0-9._\b]+$/;
Note that you don't need to hide dot (.)
in the character class. It doesn't make much sense here.
See also: -
for additional escape sequences and patterns in Regex.
+18
source to share
Check the "event.keyCode" and "value.length" boxes before checking the regular expression. Keycode 8 = backslash
$('#my-input').on('keypress change', function(event) {
// the value length without whitespaces:
var value_length = $(this).val().trim().length;
// check against minimum length and backspace
if (value_length > 1 && event.keyCode != 8) {
var regex = new RegExp('/^[a-zA-Z0-9\._]+$/');
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
}
}
0
source to share