In a wave form, fields are needs to validate at the time of entry or on submission of form. Generally in a form it needs to validate user has left required fields empty or not, user has entered valid e-mail address or not, user has entered a valid date, user has entered text in a numeric field or not and other also.
Here is a function below to validate 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. If a value is entered, the function returns true.
Function to validate required field in a form using javascript
function validate_required(field, alerttxt)
{
with (field)
{
if (value==null||value=="")
{alert(alerttxt); return false}
else {return true}
}
}
Full script, with the HTML form to validate required field
<!DOCTYPE html>
<html>
<head>
<script>
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(email, "Email must be filled out!")==false)
{email.focus();return false}
}
}
</script>
</head>
<body>
<form action="submitpage.htm" onsubmit="return validate_form(this)" method="post">
Email:<input type="text" name="email" size="40">
<input type="submit" value="submit">
</form>
</body>
</html>
Preview of the above code, to validate required field
Related Posts
- How to Create a Digital Clock in JavaScript?
- How to Detect Visitor's Browser Using JavaScript?
- What are the Different Ways to Redirect Page in JavaScript?
- How To Create Simple Image Slideshow Using JavaScript ?
- How to Create Simple JavaScript Fade Effect Animation?
- Image Slideshow with Navigation Buttons Using Javascript
- How to Create JavaScript Image Slideshow with Links
- Simple JavaScript Fade Effect Animation Using Jquery
0 Response to "How to validate required field in a form using javascript"
Post a Comment