Jump to content

simple form validation


chiprivers

Recommended Posts

I not so good at javascript cos I dont use it very often so some help with this one would be much appreciated.

 

In a form I have two fields, one date and one time.  When the form is submitted, I want to check that the date is submitted in the format 'dd/mm/yyyy' and that time is submitted as 'hhmm' (four digit number between 0000 and 2359).  If either of these fields does not contain a valid entry then the form should not submit.

Link to comment
Share on other sites

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script language="javascript" type="text/javascript">
function valDate(dateinput)
{
var splitedDate = dateinput.split("/");
if(splitedDate.length != 3)
{
	return false;
}else{
	var the_day = splitedDate[0];
	var the_month = splitedDate[1];
	var the_year = splitedDate[2];

	if(the_day > 31 || the_day < 1)
	{
		return false;
	}else if(the_month > 12 || the_month < 1){
		return false;
	}else if(the_year < 1){
		return false;
	}

	return true;
}
}

function valTime(timeinput)
{
if(timeinput.length != 4)
	return false;

var thehour = timeinput.substring(0,2);
var theminute = timeinput.substring(2,4);

if(thehour > 23 || thehour < 0)
	return false;
if(theminute > 59 || theminute < 0)
	return false;

return true;
}

function validate()
{
var the_date = document.getElementById('txt_date').value;
var the_time = document.getElementById('txt_time').value;
if(valDate(the_date) && valTime(the_time))
{
	alert("Ok!");
}else{
	alert("Wrong date!");
}
}
</script>
</head>

<body>
<input type="text" id="txt_date" size="15" />
<input type="text" id="txt_time" size="15" />

<input type="button" value="Click Me" onClick="validate()" />
</body>
</html>

 

 

Copy paste the code above and try out. Hope it works!

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.