McLaren
McLaren

Reputation: 776

Javascript date pattern

I am trying to create JavaScript pattern to see if input value is date, my date format is 2015/Jan/01, I have tried doing this \d{4}/\[A-Za-z]{3}/\d{1,2} but that did not work, Please help me in fixing it.

function SetValue() {
//  var newdata = document.getElementById('txtCellEditor').value;
    var myString = txtCellEditor.value;
    if (myString.match(\d{4}/\[A-Za-z]{3}/\d{1,2})) {
        alert("'myString' is date.");
}

Upvotes: 0

Views: 64

Answers (2)

Tushar
Tushar

Reputation: 87203

Your regex is incorrect

  1. Use delimiters of regex i.e. / at the start and end of regex
  2. Use ^ and $ to check exact match instead of substring
  3. Escape the / by preceding them with \
  4. No need to escape [
  5. Use test() instead of match

Visualization

enter image description here

Demo

var regex = /^\d{4}\/[a-z]{3}\/\d{1,2}$/i;

function SetValue() {
  var myString = document.getElementById('date').value;
  if (regex.test(myString)) {
    console.log("'myString' is date.");
  } else {
    console.log("'myString is not date.");
  }
}
<input type="text" id="date" onkeyup="SetValue()" />

Upvotes: 3

T.J. Crowder
T.J. Crowder

Reputation: 1074148

Most of the actual regular expression is fine, but you've forgotten to make it a regular expression by putting it in /s! (And you've escaped one of the / [but backward], but not the other.)

if (myString.match(/\d{4}\/[A-Za-z]{3}\/\d{1,2}/)) {
//                 ^     ^^           ^^       ^
//     regex quote-/      \--escaped--/        \-- regex quote

Upvotes: 2

Related Questions