Javascript form validation USES the example of javascript to validate mailboxes

  • 2020-03-30 01:15:10
  • OfStack

These typical form data validated by JavaScript are:

Has the user filled in the required fields in the form?
Is the email address entered by the user legitimate?
Has the user entered a valid date?
Did the user enter text in the numeric field?
Required items

The following function checks to see if the user has filled in required (or required) items in the form. If the required or required option is empty, the warning box pops up and the return value of the function is false, otherwise the return value of the function is true (meaning there is no problem with the data) :


function validate_required(field,alerttxt)
{
with (field)
{
if (value==null||value=="")
  {alert(alerttxt);return false}
else {return true}
}
}

E-mail validation (verify mailbox)

The following function checks that the data entered conforms to the basic syntax of the E-mail address.

This means that the input data must contain the @ sign and the dot sign (.). At the same time, @ cannot be the first character of the email address, and the @ must be followed by at least one dot:


function validate_email(field,alerttxt)
{
with (field)
{
apos=value.indexOf("@")
dotpos=value.lastIndexOf(".")
if (apos<1||dotpos-apos<2) 
  {alert(alerttxt);return false}
else {return true}
}
}

Example:


<html>
<head>
<script type="text/javascript">
function validate_email(field,alerttxt)
{
with (field)
{
apos=value.indexOf("@")
dotpos=value.lastIndexOf(".")
if (apos<1||dotpos-apos<2) 
  {alert(alerttxt);return false}
else {return true}
}
}
function validate_form(thisform)
{
with (thisform)
{
if (validate_email(email,"Not a valid e-mail address!")==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="30">
<input type="submit" value="Submit"> 
</form>
</body>
</html>


Related articles: