Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
134
rated 0 times [  136] [ 2]  / answers: 1 / hits: 31080  / 12 Years ago, wed, january 9, 2013, 12:00:00

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



More From » validation

 Answers
8

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;
} }
}

[#80990] Tuesday, January 8, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
hayleevalenciac

Total Points: 164
Total Questions: 89
Total Answers: 106

Location: Burkina Faso
Member since Thu, Dec 15, 2022
1 Year ago
;