How to validate an expression in JavaScript?
I have an expression in {YYYY}-{MM} format, and I have a textbox in which I will take input from user.
开发者_JAVA百科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 have to use regular expression for that. See this.
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.
if ( /{\d{2,4}}-{\d{1,2}}/.test( str_date ) == true ) {
// ok
}
else {
// fail
}
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;
}
精彩评论