Check For Required Fields (JavaScript)

Although it does add complexity to the function, we’re going to have JavaScript validate each element separately and alert the user to each individual error. That makes it much easier for the user to enter the correct information and successfully submit the form!

First, create a simple form and use the NAME attribute to name it “yourForm.” Although a form name technically isn’t required, it’s still a good idea to name your forms and form elements. Form names and element names are recommended if you plan to process the form using a CGI script.

Next, insert this JavaScript function into the document’s HEAD section:

<script language=”javascript” type=”text/javascript”>

<!– hide script from older browsers
function validateForm(yourForm)
{

if(“”==document.forms.yourForm.fullName.value)
{
alert(“Please enter your full name.”);
return false;
}

if(“”==document.forms.yourForm.email.value)
{
alert(“Please enter your email address.”);
return false;
}

if(“”==document.forms.yourForm.phoneNum.value)
{
alert(“Please enter your phone number.”);
return false;
}

}
stop hiding script –>
</script>

This function has three IF statements that are almost identical. The first IF statement checks to see if the textbox called “fullName” is blank. If so, it returns a JavaScript Alert (a pop-up box) that reminds the visitor to enter his or her name. The other two IF statements function the same way.

Note the syntax we use to refer to the form and text box:document.forms.yourForm.fullName.value

This specifically identifies the form named “yourForm” and the text box named “fullName.” It’s important to be this specific to avoid confusion – especially when there’s more than one form on the Web page.

Then, include an onSubmit statement that calls the function when the form is submitted. Include it inside the opening FORM tag:<form name=”yourForm” method=”post” action=””
onSubmit=”return validateForm(yourForm);”>

Makro

Leave a Reply