...

View Full Version : javascript client-side validation of a form



ippo
10-12-2011, 11:56 AM
Hi, :)
The following code is not working whose purpose is to validate the form with javascript. Please Help .


<html>
<head>
<script type='text/javascript'>

function formValidator()
{
// Make quick references to our fields
var firstname = document.getElementById('firstname');
var addr = document.getElementById('addr');
var zip = document.getElementById('zip');
var state = document.getElementById('state');
var username = document.getElementById('username');
var password = document.getElementById('passwd');
var email = document.getElementById('email');
var cpassword=document.getElementById('pass2');
var txtar=document.getElementById('ta');
var rad=document.getElementById('r1');
var cbox =document.getElementById('r1');
// Check each input in the order that it appears in the form!
if(isAlphabet(firstname, "Please enter only letters for your name"))
{
if(isAlphanumeric(addr, "Numbers and Letters Only for Address"))
{
if(isNumeric(zip, "Please enter a valid zip code"))
{
if(madeSelection(state, "Please Choose a State"))
{
if(lengthRestriction(username, 6, 8))
{
if(plengthRestriction(password,4,6))
{
if(confpass(cpassword,"Please confirm"))
{
if(emailValidator(email, "Please enter a valid email address"))
{
if(istextareablank(txtar,"Please enter some text"))
{
if(isradiobuttselected(rad,"Please select any one radio buttons"))
{
if(ischeckboxselected(cbox,"Please select at least one checkbox"))
{
return true;
}
}
}
}
}
}
}
}
}
}
}
return false;

}

function notEmpty(elem, helperMsg){
if(elem.value.length === 0){
alert(helperMsg);
elem.focus(); // set the focus to this input
return false;
}
return true;
}

function isNumeric(elem, helperMsg){
var numericExpression = /^[0-9]+$/;
if(elem.value.match(numericExpression)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}

function isAlphabet(elem, helperMsg){
var alphaExp = /^[a-zA-Z]+$/;
if(elem.value.match(alphaExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}

function isAlphanumeric(elem, helperMsg){
var alphaExp = /^[0-9a-zA-Z]+$/;
if(elem.value.match(alphaExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}

function lengthRestriction(elem, min, max)
{
var uInput = elem.value;
if(uInput.length >= min && uInput.length <= max){
return true;
}else{
alert("Please enter username between " +min+ " and " +max+ " characters");
elem.focus();
return false;
}
}

function plengthRestriction(elem, min,max)
{
var uInput = elem.value;
if(uInput.length >= min && uInput.length <= max){
return true;
}else{
alert("Please enter password between " +min+ " and " +max+ " characters");
elem.focus();
return false;
}
}


function madeSelection(elem, helperMsg){
if(elem.value == "Please Choose"){
alert(helperMsg);
elem.focus();
return false;
}else{
return true;
}
}

function emailValidator(elem, helperMsg){
var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
if(elem.value.match(emailExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}

function confpass(elem,helperMsg)
{
if ( confPasswd === "" )
{
alert("Please fill in the Confirm Password");
document.forms[0].elements[7].focus( );
return false;
}
else if (document.forms[0].elements[6].value != document.forms[0].elements[7].value)
{
alert( "Your passwords do not match. Please retype and try again.");
return false;
}
}

function isEmpty(s) {
return ((s === null) || (s.length === 0));
}

function istextareablank(elem,helperMsg){
var i;
<!-- Is empty? -->
if (isEmpty(s)) return true;
<!-- Search through string's' characters one by one until we find a non-whitespace character. -->
for (i=0; i < s.length; i++) {
<!-- Check that current character isn't' whitespace.-->
var currchar = s.charAt(i);
if (whitespace.indexOf(currchar) == -1)
return false;
}
<!-- All characters are whitespace. -->
return true;
}

function isradiobuttselected(elem,helperMsg){
<!-- Check to see if atleast one is checkbox checked or not-->
for (j=10; j<=11; j++) {
if(document.forms[0].elements[j].checked) {
break;
}

else if (j>=11) {
alert("Atleast Check on one of the radio buttons");
document.forms[0].elements[j].focus();
return (false);
}
}
return(true);
}

function ischeckboxselected(elem,helperMsg)
{
for (j=12; j<=13; j++) {
if(document.forms[0].elements[j].checked) {
break;
}

else if (j>=13) {
alert("Atleast Check on One of Our Services");
document.forms[0].elements[j].focus();
return (false);
}
}
return(true);
}


</script>
</head>
<body>
<form onsubmit='return formValidator()' >
<br />
First Name: <input type='text' id='firstname' /><br /><br />
Address: <input type='text' id='addr' /><br /><br />
Zip Code: <input type='text' id='zip' /><br /><br />
State: <select id='state'>
<option>Please Choose</option>
<option>AL</option>
<option>KE</option>
<option>TX</option>
<option>CH</option>
</select><br />
Username(6-8 characters): <input type='text' id='username' /><br /><br />
Password(min 4 chars):<input type="password" id='passwd' /> <br/><br />
Confirm Password: <input id="pass2" Type="password" /><br/><br />
Email: <input type='text' id='email' /><br /><br />

Something
about Yourself : <textarea name="1" cols="17" rows="4" id="ta"></textarea><br/><br />

Free Membership
<input type="radio" id="r1"/> Paid Membership <input type="radio" id="r1"/><br/><br/>
Friendship<input type="checkbox" id="box1" /> Networking <input type="checkbox" id="box1" /><br /><br />

<input type='submit' value='Submit' />
</form>
</body>
</html>

sunfighter
10-12-2011, 09:57 PM
When I first looked at this I only saw a few errors, but this has had me working all morning plus. You are going to have to compare the two files to see the errors. When I got totally lost I just did things over from scratch.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script type='text/javascript'>

function formValidator()
{
// Make quick references to our fields
var firstname = document.getElementById('firstname');
var addr = document.getElementById('addr');
var zip = document.getElementById('zip');
var state = document.getElementById('state');
var username = document.getElementById('username');
var password = document.getElementById('passwd');
var email = document.getElementById('email');
var cpassword=document.getElementById('pass2');
var txtar=document.getElementById('ta');
//var rad=document.getElementById('r1');
//var cbox =document.getElementById('r1');

// Check each input in the order that it appears in the form!
if(isAlphabet(firstname, "Please enter only letters for your name"))
{
if(isAlphanumeric(addr, "Numbers and Letters Only for Address"))
{
if(isNumeric(zip, "Please enter a valid zip code"))
{
if(madeSelection(state, "Please Choose a State"))
{
if(lengthRestriction(username, 6, 8))
{
if(plengthRestriction(password,4,6))
{
if(confpass(cpassword,"Please confirm"))
{
if(emailValidator(email, "Please enter a valid email address"))
{
if (checkForm(txtar))
{
if(isradiobuttselected())
{
if(ischeckboxselected())
{
return true;
}
}
}
}
}
}
}
}
}
}
}
return false;
}

function notEmpty(elem, helperMsg){
if(elem.value.length === 0){
alert(helperMsg);
elem.focus(); // set the focus to this input
return false;
}
return true;
}

function isNumeric(elem, helperMsg){
var numericExpression = /^[0-9]+$/;
if(elem.value.match(numericExpression)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}

function isAlphabet(elem, helperMsg){
var alphaExp = /^[a-zA-Z]+$/;
if(elem.value.match(alphaExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}

function isAlphanumeric(elem, helperMsg){
var alphaExp = /^[0-9a-zA-Z' ']+$/;
if(elem.value.match(alphaExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}

function lengthRestriction(elem, min, max)
{
var uInput = elem.value;
if(uInput.length >= min && uInput.length <= max){
return true;
}else{
alert("Please enter username between " +min+ " and " +max+ " characters");
elem.focus();
return false;
}
}

function plengthRestriction(elem, min, max)
{
var uInput = elem.value;
if(uInput.length >= min && uInput.length <= max){
return true;
}else{
alert("Please enter password between " +min+ " and " +max+ " characters");
elem.focus();
return false;
}
}


function madeSelection(elem, helperMsg){
if(elem.value == "Please Choose"){
alert(helperMsg);
elem.focus();
return false;
}else{
return true;
}
}

function emailValidator(elem, helperMsg){
var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
if(elem.value.match(emailExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}

function confpass(elem,helperMsg)
{
if ( elem.value === "" )
{
alert("Please fill in the Confirm Password");
document.forms[0].elements[7].focus( );
return false;
}
//else if (document.forms[0].elements[6].value != document.forms[0].elements[7].value)
else if (document.getElementById('passwd').value != document.getElementById('pass2').value)
{
alert( "Your passwords do not match. Please retype and try again.");
elem.focus();
return false;
}
return true;
}

function checkForm(form)
{ // validation fails if the input is blank

if(form.value == '')
{
alert("Error: Input is empty!");
form.inputfield.focus();
return false;
}
// regular expression to match only alphanumeric characters and spaces
var re = /^[\w,.;: ]+$/; // validation fails if the input doesn't match our regular expression
if(!re.test(form.value))
{
alert("Error: Input contains invalid characters!");
form.focus();
return false;
}
// validation was successful
return true;
}

function isradiobuttselected()
{
if (!document.getElementById('free').checked && !document.getElementById('paid').checked)
{
document.getElementById('radioBox').style.backgroundColor = 'yellow';
alert("Please select any one radio buttons");
return (false);
}
document.getElementById('radioBox').style.backgroundColor = '';
return (true);
}


function ischeckboxselected(elem,helperMsg)
{
if (!document.getElementById('box1').checked && !document.getElementById('box2').checked)
{
document.getElementById('chekbox').style.backgroundColor = 'yellow';
alert("Please select at least one checkbox");
return (false);
}
document.getElementById('chekbox').style.backgroundColor = '';
return (true);
}
</script>
</head>
<body>
<form id="myform" onsubmit="return formValidator()" action="">
<br />
First Name: <input type='text' id='firstname' /><br /><br />
Address: <input type='text' id='addr' /><br /><br />
Zip Code: <input type='text' id='zip' /><br /><br />
State: <select id='state'>
<option>Please Choose</option>
<option>AL</option>
<option>KE</option>
<option>TX</option>
<option>CH</option>
</select><br />
Username(6-8 characters): <input type='text' id='username' /><br /><br />
Password(min 4 chars):<input type="password" id='passwd' /> <br/><br />
Confirm Password: <input id="pass2" Type="password" /><br/><br />
Email: <input type='text' id='email' /><br /><br />

Something
about Yourself : <textarea name="1" cols="17" rows="4" id="ta"></textarea><br/><br />

<div id="radioBox" style="width:270px;">
Free Membership<input type="radio" name="r1" id="free" />
Paid Membership <input type="radio" name="r1" id="paid" />
</div>
<br/><br/>
<div id="chekbox" style="width:190px;">
Friendship<input type="checkbox" id="box1" />
Networking <input type="checkbox" id="box2" />
</div>
<br /><br />

<input type='submit' value='Submit' />
</form>
</body>
</html>

Ask any questions you have. :thumbsup:

ippo
10-12-2011, 11:18 PM
Hi sunfighter
Thanks for the help.
The program has still some errors!!
:(
If I give no input in the textarea , it is giving the alert window as expected "Error: Input contains invalid characters!"
but after that it resets the entire form!
You can check yourself by entering data in the fields and leaving the text area blank and the checkboxes and the radiobuttons not selected,then if you click "submit" ,the entire form resets instead of allowing the user to fill the rest of the form!!
That's a bug!! :eek:

sunfighter
10-14-2011, 12:35 AM
Change this function to this:


function checkForm(form)
{ // validation fails if the input is blank

if(form.value == '')
{
alert("Error: Input is empty!");
form.focus();
return false;
}
// regular expression to match only alphanumeric characters and spaces
var re = /^[\w,.;: ]+$/; // validation fails if the input doesn't match our regular expression
if(!re.test(form.value))
{
alert("Error: Input contains invalid characters!");
form.focus();
return false;
}
// validation was successful
return true;
}

ippo
10-14-2011, 09:47 AM
:thumbsup::)
Ok Sunfighter here's your due of two thanks for your help.
Thanks again.

sunfighter
10-14-2011, 04:43 PM
Thank you ippo,

A word of cation, This js does not check for everything that a validater should check for.
An example is the zip code. This script just looks to see if "only numbers" are entered. It should also check the a minimum of 5 numbers are entered and some zips have a dash and extra numbers, that should be checked for also.

It is laid out nice, but you need to work on it some more.

ippo
10-16-2011, 08:25 AM
Ok can you please give me the full code for checking all those things in the zipcode field?



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum