Forum Moderators: open
<script language="JavaScript">
<!--
function validate() {
if document.myForm.myText.value = '' {
alert('Form field blank!');
return false;
}
else
return true;
}
//-->
</script>
<form name="myForm" onSubmit="return validate()">
<input type="text" name="myText">
<input type="submit">
</form>
Can someone with a much better grasp of JS please help us on this one? I get a submission of the form no matter whether it's filled in or not, or just an "object expected" or "'(' expected" error, depending on how I modify it.
<form name=form action=address.asp method=post onsubmit="javascript:return ValidateForm(this)">
What the onsubmit method does here is waits for the results of the ValidateForm function. If it returns true, our validation has succeeded - the form entries are in an acceptable form. If it returns false, there has been an error, and the user will need to correct it before being allowed to submit the form. So now let's have a look at the ValidateForm function itself. Exactly how it will look of course will depend on the fields you need to validate.
This function can be used to check whether the user has entered anything in a given field. There are two possible types of 'emptiness' a form can return - a zero length string, or a null value. Here we simply check both these options, and return true if either of these are found to be true.
function IsEmpty(aTextField) {
if ((aTextField.value.length==0) ¦¦
(aTextField.value==null)) {
return true;
}
else { return false; }
}
function ValidateForm(form)
{
if(IsEmpty(form.aTextField))
{
alert('Form field blank!')
form.aTextField.focus();
return false;
}
return true;
}
To understand this function, remember that the return statement exits from the function and returns the code to the calling statement. Therefore, if the field 'IsEmpty', we alert the user, set the focus of the form to the appropriate field, and return false as the result. The calling statement reads the false value and does not submit the form. The user remains on the same page, with the focus pointing them to the error of their ways.
If however all the checks are verified, at the end of the ValidateForm function, we have a return true statement, meaning the form will submit successfully.