Required Field Validation

One of the important use of JavaScript is Client Side Validations.
We can validate the form’s data before sending to the server.
example: Required Field Validation (can’t leave the field blank)

<html>
<script>
function validate() {
var name = document.myForm.txtName;
if(name.value.trim()==””) {
alert(“Please enter name”);
name.focus();
return false;
} else {
return true;
}
}
</script>
<body>
<form onSubmit=”return validate()” name=”myForm”>
Enter Name : <input type=”text” id=”txtName”/> <br/>
<input type=”submit” id=”submit” value=”Submit”/>
</form>
</body>
</html>

In above example form will not get submit to the server until you fill the value in textbox.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.