Chris K.
Chris K.

Reputation: 153

jQuery mask only allow certain combinations of digits

I am trying to set up the jQuery mask plugin to only accept certain data for the last two digits of a field.

What I want is this: YYYY[03],YYYY[06],YYYY[09],YYYY[12] to be marked valid and all other inputs to be marked invalid.

Examples:

So far, what I have is this:

$('#YearMonth').mask('0000XZ', {
    translation: {
      'X': {
        pattern: /[0-1]/, optional: true
      },
      'Z': {
        pattern: /[0-9]/, optional: true
      }
    }
});

Of course; this still doesn't work correctly. If there a way to use the jQuery mask plugin to do this? Or should I try another approach?

Thank you

Upvotes: 1

Views: 666

Answers (2)

isvforall
isvforall

Reputation: 8926

Plain javascript, using regex

/\d{4}03|06|09|12/  

function validation(s) {
    var r = /\d{4}03|06|09|12/;
    return s.match(r) ? s + ": Valid" : s + ": Invalid";
}

//test
["201612", "201511", "200403", "201102"].forEach(e =>
    document.write(validation(e) + '<br>'));

Upvotes: 1

guest271314
guest271314

Reputation: 1

You can use pattern attribute with RegExp \d{4}(0[369]|12); add required attribute to prevent submission if input value is empty string. You can also use oninput event to clear input field if value does not match pattern. The form should not submit if input value does not match RegExp at pattern attribute.

document.getElementById("YearMonth")
.oninput = function(e) {
  if (this.value.length === this.maxLength 
      && !new RegExp(this.pattern).test(this.value)) {
        alert("Invalid input\n" + this.title);
        this.value = "";
  }
}
<form>
  <label for="YearMonth">
    <input id="YearMonth" type="text" pattern="\d{4}(0[369]|12)" minlength="6" maxlength="6" title="Input: YYYY[03] OR YYYY[06] OR YYYY[09] OR YYYY[12]" placeholder="YYYY[03,06,09,12]" required />
  </label>
  <input type="submit" />
</form>

Upvotes: 0

Related Questions