I want to do year validation whre it should be only numeric and Its should be 4 digit long and between 1920 to current year for that I have create Javascript function as follows:
function yearValidation(year) {
var text = /^[0-9]+$/;
if (year != 0) {
if ((year != "") && (!text.test(year))) {
alert("Please Enter Numeric Values Only");
return false;
}
if (year.length != 4) {
alert("Year is not proper. Please check");
return false;
}
var current_year=new Date().getFullYear();
if((year < 1920) || (year > current_year))
{
alert("Year should be in range 1920 to current year");
return false;
}
return true;
}
and called it on onkeypress="return yearValidation(this.value)"
But when I enter 1 it gives me alert:
Year should be in range 1920 to current year
Brian Tompsett - 汤莱恩
5,92772 gold badges64 silver badges135 bronze badges
asked Jan 9, 2013 at 6:17
Edward
1,3778 gold badges26 silver badges44 bronze badges
3 Answers 3
Applying two event should solve the problem.
HTML:
<input type="text"
onblur="yearValidation(this.value,event)"
onkeypress="yearValidation(this.value,event)"
>
JS:
function yearValidation(year,ev) {
var text = /^[0-9]+$/;
if(ev.type=="blur" || year.length==4 && ev.keyCode!=8 && ev.keyCode!=46) {
if (year != 0) {
if ((year != "") && (!text.test(year))) {
alert("Please Enter Numeric Values Only");
return false;
}
if (year.length != 4) {
alert("Year is not proper. Please check");
return false;
}
var current_year=new Date().getFullYear();
if((year < 1920) || (year > current_year))
{
alert("Year should be in range 1920 to current year");
return false;
}
return true;
} }
}
answered Jan 9, 2013 at 7:05
vusan
5,3574 gold badges50 silver badges83 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Guess it's:
if (year.length < 4) {
not
if (year.length != 4) {
answered Jan 9, 2013 at 6:23
Vimalnath
6,4732 gold badges29 silver badges47 bronze badges
Comments
Or directly in form
<input name="date_check"
type="text"
title="Date must be in this case:dd.mm.yy"
pattern="^[0-9]{1,2}\.[0-9]{2}$" />
Comments
lang-js
1it's not empty, it's not 4, and it's less than1920so it's seems correct.onchangeinstead ofonkeypress.onBlurof your text input.