Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

validate the field for valid years

Status
Not open for further replies.

markshen2004

Programmer
Jun 9, 2004
89
CA
I need a field to input the year,I hope the valid value is from 1990 to currect year.

I need write a javascript to validate the field .

Please give me a idea about it.

Thanks a lot
 
Here is an example page that you can save. Is shows 3 different ways of calling the small Javascript function... using an onchange, using a button in the form, or using a href. You can of course call it directly from any other javascript code and modify it to return true or false.

I hope this gets you started

Code:
<html>
<head>
<title>Test</title>

<script type="text/javascript">
// checks to see if the data passed in is a 4 digit year between now and 1900
function checkIsValid(_data)
{
 var _thisYear = new Date().getFullYear();
	
 if (_data.length != 4) return "This is not valid";
 if (!_data.match(/\d{4}/)) return "This is not valid";
 if (parseInt(_data) > _thisYear || parseInt(_data) < 1900)
  return "This is not valid";
 return "This is valid";
}
</script>
</head>

<body>
<form name="myForm">
<input type="text" name="theYear" maxlength="4" value="" onchange="alert(checkIsValid(this.value));"/>
<input type="button" value="Test if Valid" onclick="alert(checkIsValid(this.form.theYear.value));" />
</form>
<p>Click <a href="javascript: alert(checkIsValid(document.myForm.theYear.value)); ">here</a> to check content is valid</p>
</body>
</html>

Jeff
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top