JavaScript Form Validation


HTML form validation can be done by JavaScript.

Name Field validation

Empty Name Validation

If a form field (fname) is empty, this function alerts a message, and returns false, to prevent the form from being submitted:


JavaScript Example

function validate()
{
if(document.myform.fname.value =="")
{
alert("Please Enter the Name");
document.myform.fname.focus();
return false;
}
}

The function can be called when the form is submitted:

HTML Form Example


<form name="myForm" onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>

Run Example>>




Name Filed should contain only alphabates

Validate Name field.it should only contained alphabates and if name is grater than 30 character it should throw an error message.

Example

Note:- Not take space in name


<script>
function validateForm()
{
if(!document.myform.nam.value.match(/^[a-zA-z]+$/))
{
alert("Please Enter Alphabates only");
document.myform.nam.focus();
return false;
}else if(document.myform.nam.value.length>30)
{
alert("You Can Enter maximum 30 characters name");
document.myform.nam.focus();
return false;
}else{
var name=document.getElementById('nam').value;
document.write(name);
}
}
</script>
<form name="myform" onsubmit="return validateForm()" method="post">
Enter Your Name: <input type="text" name="nam" id="nam" />
<input type="submit" value="Submit">
</form>

Run Example>>