Stefano De Rosso
Stefano De Rosso

Reputation: 1339

Allow only regex pattern in javascript

I want the user to input a number with format:

##/####

Where the "#" are numbers.

Here is the sample code:

(function() {
  var previousValue = document.getElementById('myInput').value;
  var pattern = /^\d{2}(\/\d{4})?$/;

  function validateInput(event) {
    event = event || window.event;
    var newValue = event.target.value || '';

    if (newValue.match(pattern)) {
      // Valid input; update previousValue:
      previousValue = newValue;
    } else {
      // Invalid input; reset field value:
      event.target.value = previousValue;
    }
  }

  document.getElementById('myInput').onkeyup = validateInput;
}());
<input id="myInput" type="text" maxlength=7 value="" />

I can only write the first two numbers, but I can't type anything else after that, even though the regular expression seems correct to me.

---EDIT---

After all the answers, I want to point out that I already have a validator that fires on the submit, which tells the user if they have typed in the correct form; I just wanted to somehow "guide" the user in the typing of the input.

Upvotes: 0

Views: 103

Answers (5)

yajiv
yajiv

Reputation: 2941

Use this var pattern = /^\d{0,2}(\/\d{0,4})?$/; when user is typing which basically allow to type the pattern you want. And when input become blur check length of input field and validate accordingly.(or you can use minlength(make it equal to maxlength) if you are using input field in form then you will not require blur method)

(function() {
    var previousValue = document.getElementById('myInput').value;
    var pattern = /^\d{0,2}(\/\d{0,4})?$/;

    function validateInput(event) {
        len = event.target.value.length;
        event = event || window.event;
        var newValue = event.target.value || '';

        if (newValue.match(pattern)) {
            // Valid input; update previousValue:
            previousValue = newValue;
        } else {
            // Invalid input; reset field value:
            event.target.value = previousValue;
        }
    }

    document.getElementById('myInput').onkeyup = validateInput;
}());


(function() {
    function validateInput(event) {
        len = event.target.value.length;

        (len===7) ? console.log("Success") : console.log("fail");
    }
    document.getElementById('myInput').onblur = validateInput;
}());
<input id="myInput" type="text" milength=7 maxlength=7 value="" />
<button>1</button>

Upvotes: 1

Romeo Sierra
Romeo Sierra

Reputation: 1756

To me, your approach of validating seems wrong! You have to wait to do the validation until the user blurs away from the input field.

What I am suggesting is to use the event onblur instead of onkeyup, to perform your validation. How can you validate an input which is not completed?

Or else, you could program the event onkeypress, to check the key which is struck is one you need. You will have to deal with key codes and all.

EDIT

Managed to tackle the problem! Check if the following helps.

(function() {
    var previousValue = document.getElementById('myInput').value;
    function validateInput(event) {
        event = event || window.event;
        var newValue = event.target.value || '';
        var previousValueLength = document.getElementById('myInput').value.length;
        var pattern = /^\d{2}\/\d{4}$/;
        switch(previousValueLength){
            case 0:
                pattern = /^$/;
                break;
            case 1:
                pattern = /^\d{1}$/;
                break;
            case 2:
                pattern = /^\d{2}$/;
                break;
            case 3:
                pattern = /^\d{2}\/$/;
                break;
            case 4:
                pattern = /^\d{2}\/\d{1}$/;
                break;
            case 5:
                pattern = /^\d{2}\/\d{2}$/;
                break;
            case 6:
                pattern = /^\d{2}\/\d{3}$/;
                break;
        }
        if (newValue.match(pattern)) {
            // Valid input; update previousValue:
            previousValue = newValue;
        } else {
            // Invalid input; reset field value:
            event.target.value = previousValue;
        }
    }

    document.getElementById('myInput').onkeyup = validateInput;
}());

https://jsfiddle.net/zjg6azjn/9/

Upvotes: 0

Ludovit Mydla
Ludovit Mydla

Reputation: 822

Probably you want to allow regex to validate correct when the user is still not finished with writing it down.

var pattern = /^\d{0,2}(\/\d{0,4})?$/;

But you would still need to validate it after that, so onblur check might be better.

Upvotes: 1

Vasyl Moskalov
Vasyl Moskalov

Reputation: 4630

From my point of view your problem is in event that you handle. Onkeyup fired after any key up. And if the current value of input field is not matched with your pattern you replace it with old one value. I think you need to handle change event instead of keyup: codepen

Upvotes: 0

Mario Cianciolo
Mario Cianciolo

Reputation: 1261

First of all, you can analyze your regex here.

You will find that your regex:

/^\d{2}\/\d{4}?$/

matches a string that begins with two digits, followed by a slash and then 4 digits repeated zero or one time (the question mark).

Just remove the question mark in order to match the exact pattern.

Upvotes: 0

Related Questions