Babu Reddy Babu Reddy - 6 months ago 14
jQuery Question

Validate Year from the given date using Jquery

How to validate year in the date using jquery?

For example if i have date like

"01/05/0001"
it should give a error.

Answer

Let's assume that valid years are between 1500 and the current year which is here 2015, so the validation will be like this:

Code:

var str = "01/05/0001";
var year = str.match(/\/(\d{4})/)[1];
var currYear = new Date().toString().match(/(\d{4})/)[1];
if (year >= 1500 && year <= currYear) {
  alert(year + ' is valid.');
} else {
  alert(year + ' is an invalid year !');
}

Explanation:

We take the date and extract the year and compare it to a given previous year and the current one.

Comments