How to validate form using JavaScript

How to validate form using JavaScript

Here now you will learn how you can validate a form using JavaScript, its client-side validation, and better than the server-side validation because the server-side validation is somehow time-consuming.

First, you should have a form to check for example here we have

<form method="post" action="mailto:[email protected]" name="ContactForm" onsubmit="return ValidateContactForm();">
<p>Name: <input type="text" size="65" name="Name"></p>
<p>E-mail Address: </p>
<p>
<input type="text" size="65" name="Email"><br>
Telephone: <input type="text" size="65" name="Telephone"><br>
<input type="checkbox" name="DoNotCall"> Please do not call me.</p>
<p>What can we help you with?<br>
<select type="text" value="" name="Subject"><option> </option><option>Customer Service</option><option>Question</option><option>Comment</option><option>Consultation</option><option>Other</option></select></p>
<p>Comments: <textarea cols="55" name="Comment">  </textarea></p>
<p><input type="submit" value="Send" name="submit"><input type="reset" value="Reset" name="reset"></p>
</form>

then you may now check either user puts valid data or not by using the script,

<script type="text/javascript">
function ValidateContactForm()
{
var name = document.ContactForm.Name;
var email = document.ContactForm.Email;
var phone = document.ContactForm.Telephone;
var nocall = document.ContactForm.DoNotCall;
var what = document.ContactForm.Subject;
var comment = document.ContactForm.Comment;</p>
<p>if (name.value == "")
{
window.alert("Please enter your name.");
name.focus();
return false;
}</p>
<p>if (email.value == "")
{
window.alert("Please enter a valid e-mail address.");
email.focus();
return false;
}
if (email.value.indexOf("@", 0) < 0)
{
window.alert("Please enter a valid e-mail address.");
email.focus();
return false;
}
if (email.value.indexOf(".", 0) < 0)
{
window.alert("Please enter a valid e-mail address.");
email.focus();
return false;
}

if ((nocall.checked == false) &#038;&#038; (phone.value == ""))
{
window.alert("Please enter your telephone number.");
phone.focus();
return false;
}

if (what.selectedIndex < 1)
{
alert("Please tell us how we can help you.");
what.focus();
return false;
}

if (comment.value == "")
{
window.alert("Please provide a detailed description or comment.");
comment.focus();
return false;
}
return true;
}

</script>

so now you will be able to validate your form on the client-side as it’s easy to learn and handle.

the function in the script can call in the submit event of the form and the action converted to the # sign.

I found this is easy so I share it with you to learn from it.

Hope you learn from it.