preload

Javascript Form Validation

Posted by Prozilla 2.0 on Feb 03, 2010

Using forms
to collect data is required for specific information and formatting, which can be used for sending message, populating databases, calculations etc., however missing and improper field data can cause problems with generating information. This W3 tutorial shows how to use javascript to check

Required Fields

function validate_required(field,alerttxt)

{

with (field)

{

if (value==null||value==”")

{

alert(alerttxt);return false;

}

else

{

return true;

}

}

}

The entire script, with the HTML form could look something like this:

<html>

<head>

<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(email,”Email must be filled out!”)==false)

{email.focus();return false;}

}

if (validate_required(name,”Name must be filled out!”)==false)

{email.focus();return false;}

}

}

</script>

</head>

<body>

<form action=”submit.htm”
onsubmit=”return validate_form(this)”
method=”post”>
email: <input type=”text” name=”email” size=”30″>

name: <input type=”text” name=”name” size=”30″>
<input type=”submit” value=”Submit”>

</form>

</body>

</html>


E-mail Validation

The function below checks if the content has the general syntax of an email and looks for @ sign and a dot (.).
Also, the @ must not be the first character of the email address, and the last
dot must at least be one character after the @ sign:

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;}

}

}

The entire script, with the HTML form could look something like this:

<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=”submit.htm”
onsubmit=”return validate_form(this);”
method=”post”>

Email: <input type=”text” name=”email” size=”30″>

<input type=”submit” value=”Submit”>

</form>

</body>

</html>

  • Leave a Reply

    * Required
    ** Your Email is never shared