javascript regex for MM/YYYY and YYYY -


i have 2 places need regex in javascript 1 validate mm/yyyy have:

var regex = new regexp(/^(0?[1-9]|1[0-2])\/(\d{4})$/); 

the other validate yyyy

i need both validate year between 1900 , current year

this work next millennium:

var y = (new date().getyear()-100).tostring(); // "13" var strreg = '^((0?[1-9]|1[0-2])\\/)?(19\\d{2}|2' + (y.length-2?'':'0'); for(var i=0;i<y.length;i++) {     strreg+='[0-'+y[i]+']'; } strreg+=')$'; // "^((0?[1-9]|1[0-2])\/)?(19\d{2}|20[0-1][0-3])$" console.log(new regexp(strreg).test('2013')); // true console.log(new regexp(strreg).test('2016')); // false console.log(new regexp(strreg).test('01/2013')); // true console.log(new regexp(strreg).test('13/2013')); // false 

and if want use valid dates century , last century (versus 1900s til now), can replace 19 in regex code... '...?(' + (y.length-2?parseint(y[0])+19:'19') + '\\d{2}|...'


Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

java - Digest auth with Spring Security using javaconfig -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -