Titti Towel
Titti Towel

Reputation: 121

Regular Expression max-length is not working

function test() {
    var regex = new RegExp("^[0-9]{1,11}$");
    var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
    if (!regex.test(key)) {
        event.preventDefault();
        return false;
    }
}

It is correct to take only integer but max-length is not working. It takes more than 11 digits.

Upvotes: 2

Views: 4976

Answers (3)

user663031
user663031

Reputation:

This kind of manual input validation is not how applications are usually written these days in HTML5. It is a throwback to the bad old jQuery days. It is a bad user experience to simply throw away keystrokes--the user has no idea what he is doing wrong, and may think his keyboard is broken. If you trap on the keyup event, you will also miss some scenarios, such as when the user has dragged and dropped text into the input box. Or if the user types CTRL+V to paste text into the box, you will end up looking at that keystroke instead of the characters pasted in.

HTML5 adds the pattern attribute to the input element which allows you to do regexp-based validation. This has a number of advantages. For instance, invalid entries can be styled using CSS with the :invalid pseudo-class. Invalid form entries will automatically prevent submits, and put up user-friendly balloons describing the specific problem.

In your case:

<input pattern="\\d{1, 11}">

Note that no ^ or $ anchors are required--they are implicit in this case.

No JS is required.

Upvotes: 1

Andy
Andy

Reputation: 531

This is what I understood from your question. Try something like this.

var count = 0;

function test() {
    var regex = new RegExp("^[0-9]{1,11}$");
    var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);

   if(count<11){
    if (!regex.test(key)) {
        count=0;
        event.preventDefault();
        return false;
    }
     count++;
   }
   return false;   
}

Upvotes: 0

Hitmands
Hitmands

Reputation: 14159

as you said:

I want to give permission only to write digits and max length should be eleven(11) digits.

you can:

  1. use an <input type="number" maxlength="11" />
  2. use a regex /^\d{1,11}$/

document.addEventListener('DOMContentLoaded', function() {
function valueIsValid(v) {

  return /^\d{1,11}$/.test(v);
}
  var foo = document.querySelector('#foo');

foo
  .addEventListener('change', function() {
    console.log('valid', valueIsValid(foo.value), foo.value)
  })
;
});
<input id="foo" />

Upvotes: 0

Related Questions