0

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.

5
  • 3
    "But I only get to write the first two numbers" — I can't reproduce that problem. As soon as I type one number, it fails to match the pattern and gets set back to the default value (blank). Commented Apr 6, 2018 at 7:44
  • Yes, it's correct if you copy and paste the whole date at once. Commented Apr 6, 2018 at 7:45
  • Exactly... This is a problem with how the events are employed! Commented Apr 6, 2018 at 7:45
  • Should I be able to type the date in reverse order? (8, left, 1, left, 0, left, 2, left, /, left, 1, left, 1) Commented Apr 6, 2018 at 7:50
  • You should validate the value on blur... or maybe, validate on key up but avoid changing the value inside the textfield Commented Apr 6, 2018 at 7:53

5 Answers 5

1

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>

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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.

1 Comment

Wrong... .
0

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

Comments

0

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.