0

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.");
}
1
  • Why such an unusual date format? Commented Jul 24, 2015 at 9:45

2 Answers 2

3

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()" />

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

1 Comment

Good catch on the missing anchors.
2

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

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.