Regex in javascript that allows backspace

My regex that allows characters, numbers, periods and underscore

var numericReg = /^[a-zA-Z0-9\._]+$/;

      

How can I allow backspace in this reg ex.?

+3


source to share


5 answers


The optimal solution to this problem is to check the value of textbox> 0 before checking. This will help resolve the error showing when backspace is pressed in an empty text field. !!



0


source


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


I would suggest that you rewrite your regex:

var numericReg = /^[a-zA-Z0-9._]+|[\b]+$/

      

Or:

var numericReg = /^(?:[a-zA-Z0-9._]|[\b])+$/

      

0


source


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


I also made an input type text that only accepts numbers (not decimal) and a reverse keyboard. I notice that placing [\ b] in regex is not required in a non-browser browser.

var regExpr = new RegExp("^[0-9,\b][0-9,\b]*$");

      

0


source







All Articles