views:

66

answers:

4

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

+2  A: 

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

Sarfraz
Thank You. But, i am new to Regular Expression.Can you help.
Peak
@Kapil123: click the link.
nickf
A: 

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;
}
Alsciende
Thank You. I got it.
Peak
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...
gnarf
A: 

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.

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