-1

Every time user enter, value is checked with regular expression, I'm trying to restrict user from entering further into input field if regexp is not matched

Using keyup event, preventdefault never fires and using keypress event, user is unable to input at all because in the begining, value in input field shows as "" (nothing)

on keyup val="2"

on keypress val="1"

var discountRegex = /(^100([.]0{1,2})?)$|(^\d{1,2}([.]\d{1,2})?)$/
            $("#" + (idOfElement)).on("keyup",function (e) {

                var val=this.value
                var k = e.keyCode
                if(k==46 ||(k > 48 && k <97)){
                    console.log(k)
                    return discountRegex.test(val);
                }

            });

in the above code idOfElement is the id i get on whichever field i focus.

2 Answers2

0

You can check if the regex is matched and if not you can remove the last char like the example below

I updated the code with keydown example

Example

Marco Moretti
  • 689
  • 4
  • 11
0

Please refer sample code. If input key is invalid input will not accept it. Also please find fiddle for same in comment.

<input type="text">


$(document).ready(function(){
  $("input").bind('keypress', function(e) {
  var str = e.keyCode;
  if (/(^100([.]0{1,2})?)$|(^\d{1,2}([.]\d{1,2})?)$/.test(str)) {
          alert('Invalid')
       e.preventDefault();
    } else {
       alert('Valid');
    }
});
}); 
Shiv Patne
  • 543
  • 3
  • 10