Info city. يتم التشغيل بواسطة Blogger.

How to validate required field in a form using javascript

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 






Email:






Related Posts



0 التعليقات