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
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;
}
/\{(\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...