1

I have an expression in {YYYY}-{MM} format, and I have a textbox in which I will take input from user.

The user must input in above format for example: {2010}-{03} or {10}-{3} or {2010}-{3}

How do I validate this using JavaScript?

Thank You

4 Answers 4

2

You will have to use regular expression for that. See this.

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

1 Comment

Thank You. But, i am new to Regular Expression. Can you help.
1

To add a bit for details to Sarfraz answer your example would give this regular expression

var str = "2010-03".match(/\{\d{2,4}\}-\{\d{1,2}\}/g);

it would give you array with matching part if it match.

Comments

1
if ( /{\d{2,4}}-{\d{1,2}}/.test( str_date ) == true ) {
  // ok
}
else {
  // fail
}

Comments

0

You will match the input against a regular expression :

if(myInput.value.match(/\{\d+\}-\{\d+\}/)) {
  // input validated
} else {
  // validation failed
}

This regexp can be adjusted depending on what you need. Here is a quick tutorial of javascript regexp : http://www.w3schools.com/js/js_obj_regexp.asp .

Also, if you want to check if the input represents a valid date, you will have some extra work. It looks like you're accepting anything that looks like a year-month, so you can try this:

if(myInput.value.match(/\{(\d+)\}-\{(\d+)\}/)) {
  var year = parseInt(RegExp.$1);
  var month = parseInt(RegExp.$2);
  if(month<1 || month>12) return false;
  if(year < 100) year += 2000;
  if(year > 3000) return false;
  return true;
} else {
  // validation failed
  return false;
}

1 Comment

You could let the RegExp handle more of the validation: /\{(\d{2,4})\}-\{(0?[1-9]|1[12])\}/ Only allows 1-12 for the month part, and only allows 2 digit or 4 digit years for example...

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.