1

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
3
  • Well, 1 it's not empty, it's not 4, and it's less than 1920 so it's seems correct. Commented Jan 9, 2013 at 6:21
  • 2
    Do it onchange instead of onkeypress. Commented Jan 9, 2013 at 6:22
  • do it onBlur of your text input. Commented Jan 9, 2013 at 6:25

3 Answers 3

6

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
Sign up to request clarification or add additional context in comments.

Comments

0

Guess it's:

 if (year.length < 4) {

not

if (year.length != 4) {
answered Jan 9, 2013 at 6:23

Comments

0

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}$" />
answered Mar 15, 2020 at 15:27

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.