- Validating whether or not the user left required fields empty
- Whether or not the user entered a valid e-mail address
- Checking whether or not the user entered a valid date
- Whether or not the user entered text in a numeric field or entered number in the text field
Here in this post, I am going to describe to you, “How to Validate Required Fields using JavaScript”.
Read Also: How to Write JavaScript With HTML?
Table of Contents
Validating Required Field using JavaScript
This JavaScript Function below checks if a required field has been left empty. If the required field is blank, an alert box alerts a message and the function returns false. When you enter some values in the form fields the function returns true.
function validate_required(field, alerttxt)
{
with(field)
{
if (value===null||value==="")
{alert(alerttxt); return false;}
else {return true;}
}
}
Read Also: How to Write Conditional Statements in JavaScript?
Complete JavaScript Code with HTML for Validating Required Field
Here are the complete JavaScript codes along with complete HTML codes uses with the JavaScript Functions given below.
<html>
<head><title>Subscription Form</title>
<script type="text/javascript">
function validate_required(field, alerttxt)
{
with(field)
{
if (value===null||value==="")
{alert(alerttxt); return false;}
else {return true;}
}
}
function validate_form(thisform)
{
with(thisform)
{
if (validate_required(fname, "First name must be filled out!")===false)
{fname.foucus(); return false;}
if (validate_required(lname, "Last name must be filled out!")===false)
{lname.foucus(); return false;}
if (validate_required(password, "Password must be filled out!")===false)
{password.foucus(); return false;}
if (validate_required(rpassword, "Retype Password must be filled out!")===false)
{rpassword.foucus(); return false;}
}
}
</script>
</head>
<body>
<FORM METHOD='GET' ONSUBMIT="return validate_form(this);">
<DIV>First Name:<INPUT TYPE='text' NAME='fname' SIZE=30 MAXLENGTH=25></DIV><br/>
<DIV>Last Name:<INPUT TYPE='text' NAME='lname' SIZE=30 MAXLENGTH=25></DIV><br/>
<DIV>Password:<INPUT TYPE='password' NAME='password' SIZE=30 MAXLENGTH=25></DIV><br/>
<DIV>Retype Password:<INPUT TYPE='password' NAME='rpassword' SIZE=30 MAXLENGTH=25></DIV><br/>
<DIV>Email:<INPUT TYPE='text' NAME='email' SIZE=30 MAXLENGTH=25></DIV><br/>
<br/>
<INPUT TYPE='submit' VALUE='Submit'><INPUT TYPE='reset' VALUE='Reset'>
</FORM>
</body>
</html>
Preview
Following is the preview of the HTML and JavaScript code above. It will show the alert message when you try to submit a form without entering the required fields “First Name”, “Last Name”, “Password” and “Retype Password”.
Here I have posted this JavaScript and HTML codes for sample only. You can write validation JavaScript to validate other fields for other circumstances.
Read Next: How to create Changeable Date and Time Using JavaScript?