Javascript validate empty form fields

Javascript validate empty form fields

Check for Empty Fields Using JavaScript

To make the web browser check that a field is not empty, you will need to add a call to your validation function when the form is submitted. Do this by adding a “onsubmit” attribute to your FORM tag, like the following :

<form action=”” method=”post” name=”form1″ onsubmit=”return validateform(this);” >

If the field you want to validate is something like:

<input type=”text” name=”Email” />

 

In the <head> section of your code:

<script language=”JavaScript” type=”text/javascript”>
<!–
function validateform ( form )
{

if (form.Email.value == “”) {
alert( “Please enter your email address.” );
form.email.focus();
return false ;
}
//Add More Fields here

 

//End Add Fields
return true ;
}
//–>
</script>

To validate other text boxes change the ( Field ) below to reflect the field name you want to validate and cut and paste it into your validate function:

if (form.Field.value == “”) {
alert( “Please enter your Field.” );
form.Field.focus();
return false ;
}