Go Back   CodingForums.com > :: Client side development > JavaScript programming

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 05-01-2011, 05:51 PM   PM User | #1
TheBewitching1
New to the CF scene

 
Join Date: May 2011
Posts: 2
Thanks: 0
Thanked 0 Times in 0 Posts
TheBewitching1 is an unknown quantity at this point
Question Help with Javascript validation

I have a validation issue. I need the input fields to highlight yellow if no text has been entered and when the form is submitted the error message displays to check the highlighted fields.
I get the input boxes to highlight when there is no text but on submit the form goes to the next page without the error alert message.
Any suggestions would be appreciated.

My HTML page:
Code:
<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<!-- 


   Filename:         works.htm
   Supporting files: 
-->

   <!-- #BeginEditable "doctitle" -->

   <title>Wizard Works Order Form</title>
   <!-- #EndEditable -->
   <link href="ww.css" rel="stylesheet" type="text/css" />
   <script src="functions.js" type="text/javascript"></script>
   <script src="valid.js" type="text/javascript"></script>

 </head>
<body>
   <form id="order" action="file:///F:/JavaScript/case4/done.htm" onsubmit="return validateForm()" method="post">
   <div id="page">

      <div id="head">
         <img alt="Wizard Works" src="logo.jpg" />
      </div>

      <ul id="links">
         <li><a href="#">Home</a></li>
         <li><a href="#">Assortments</a></li>
         <li><a href="#">Firecrackers</a></li>
         <li><a href="#">Fontains</a></li>
         <li><a href="#">Cones</a></li>
         <li><a href="#">Rockets</a></li>
         <li><a href="#">Sparklers</a></li>
         <li><a href="#">Online Store</a></li>
         <li><a href="#">Shopping Cart</a></li>
         <li><a href="#">Your Account</a></li>
         <li><a href="#">Safety</a></li>
         <li><a href="#">Tech Support</a></li>
         <li><a href="#">Customer Service</a></li>
         <li><a href="#">About Us</a></li>
         <li><a href="#">Contact Us</a></li>
      </ul>



      <div id="webform">
         <fieldset id="purchase">
            <legend>Order</legend>
            <label id="produtLab" class="required" for="product">1) Product</label>
            <select id="product">
               <option value="">Select a Product</option>
               <option value="3.5">Green/Purple Fountain: $3.50 ea.</option>
               <option value="4.95">Silver Cone: $4.95 ea.</option>
               <option value="6.95">Glitter Cone: $6.95 ea.</option>
               <option value="9.95">Glittering Stars: $9.95 ea.</option>
               <option value="19.95">Fountain Kit: $19.95 ea.</option>
               <option value="29.95">Fountain Kit Deluxe: $29.95</option>
               <option value="39.95">Giant Fountain: $39.95</option>
            </select>
            <br />
            <label id="qtyLab" class="required" for="qty">2) Quantity</label>
            <select id="qty">
               <option value="">Select a Quantity</option>
               <option value="1"> 1</option>
               <option value="2"> 2</option>
               <option value="3"> 3</option>
               <option value="4"> 4</option>
               <option value="5"> 5</option>
               <option value="6"> 6</option>
               <option value="7"> 7</option>
               <option value="8"> 8</option>
               <option value="9"> 9</option>
               <option value="10">10</option>
            </select>  
            <br />
            <label id="shippingLab" class="required" for="shipping">2) Shipping</label>
            <select id="shipping">
               <option value="">Select a Shipping Option</option>
               <option value="4.95">Standard ($4.95)</option>
               <option value="8.95">Express ($8.95)</option>
               <option value="12.95">Next Day ($12.95)</option>
            </select> 
            <br />
            <label id="totalLab" for="total">3) Total Calculated Cost</label>
            <input id="total" readonly="readonly" size="20" type="text" />
         </fieldset>

         <fieldset id="contact">
         <legend>Contact Information</legend>
            <label id="fnameLab" class="required" for="fname">4) First Name</label>
            <input id="fname" size="20" type="text" class="validate" onblur="changeColor(this)" />
            <br />
            <label id="lnameLab" class="required" for="lname">5) Last Name</label>
            <input id="lname" size="20" type="text" onblur="changeColor(this)"   />
            <br />
            <label id="addressLab" class="required" for="address">6) Address</label>
            <textarea id="address" cols="20" rows="5"onblur="changeColor(this)" ></textarea>
            <br />
            <label id="phoneLab" class="required" for="phone">7) Phone (nnn) nnn - nnnn</label>
            <input id="phone" size="20" type="text" onblur="changeColor(this)" />
         </fieldset>

         <fieldset id="credit">
         <legend>Payment Information</legend>
            <label for="ccard">8) Credit Card</label>
            <select id="ccard">
               <option value="ae">American Express</option>
               <option value="dc">Diners Club</option>
               <option value="disc">Discover</option>
               <option value="mc">MasterCard</option>
               <option value="visa">Visa</option>
            </select>
            <br />
            <label id="cholderLab" class="required" for="cholder">9) Card Holder</label>
            <input id="cholder" size="20" type="text"onblur="changeColor(this)"  />
            <br />
            <label id="cnumLab" class="required" for="cnum">10) Card Number</label>
            <input id="cnum" size="20" type="text"onblur="changeColor(this)"  />
            <br />
            <label class="required">11) Expiration Date</label>
            <select id="cmonth" name="cmonth">
               <option>01</option><option>02</option><option>03</option>
               <option>04</option><option>05</option><option>06</option>
               <option>07</option><option>08</option><option>09</option>
               <option>10</option><option>11</option><option>12</option>
            </select>
            /
            <select id="cyear" name="cyear">
               <option>2010</option><option>2011</option><option>2012</option>
               <option>2013</option><option>2014</option><option>2015</option>
            </select>
         </fieldset> 

         <input id="sbutton" type="submit" value="Submit Order" onclick="returm validateForm();return false;"/>
      </div>
   </div>
   </form>

</body>
</html>
My valid.js code:
Code:
/*


   Functions List:

   initForm()
      Initiates the Web form for use by the customer

   calcCost()
      Calculates the cost of the customer order

   validLengths()
      Validates that empty values have been entered for required
      fields

   testLength(field)
      Tests the length of the text string in the specified field

   validPatterns()
      Validates that the field values match their regular expressions

   testPattern(field, reg)
      Tests a text string against a specified regular expression

   validCNum()
      Tests that the specified credit card number passes the Luhn formula

   validateForm()
      Performs a validation test on all of the fields in the form


*/


window.onload = initForm;
var wform;
var productIndex = 1;
var qtyIndex = 1;
var shipIndex = 1;

function initForm() {
   wform = document.forms[0];
   wform.product.onchange = calcCost;
   wform.qty.onchange = calcCost;
   wform.shipping.onchange = calcCost;
   wform.onsubmit = validateForm;
}

function calcCost() {
   productIndex = wform.product.selectedIndex;
   productCost = parseFloat(wform.product.options[productIndex].value);

   qtyIndex = wform.qty.selectedIndex;
   qtyVal = parseFloat(wform.qty.options[qtyIndex].value);

   shipIndex = wform.shipping.selectedIndex;
   shipVal = parseFloat(wform.shipping.options[shipIndex].value);

   if (productIndex != 0 && qtyIndex != 0 && shipIndex != 0) {
      wform.total.value = "$"+(productCost*qtyVal+shipVal).toFixed(2);
   }
}


function validLengths() {
   var isValid = true;
   
   if (testLength(wform.total)== false) isValid = false;
   if (testLength(wform.fname)== false) isValid = false;
   if (testLength(wform.lname)== false) isValid=false;
   if (testLength(wform.address)== false) isValid=false;
   if (testLength(wform.phone)== false) isValid=false;
   if (testLength(wform.cholder)== false) isValid=false;
   if (testLength(wform.cnum)== false) isValid=false;
  
   return isValid;
}

function testLength(field) {
   var isValid = true;
   if (field.value.length == 0) {
      document.getElementById(field.id+"contact").style.bgcolor="yellow";
      isValid = false;
   } else {
      document.getElementById(field.id+"contact").style.bgcolor="white";
   }
   return isValid;
}

function validPatterns() {
   var isValid = true;

   phonereg = /^\(?\d{3}[\)-]?\s?\d{3}[\s-]?\d{4}$/;
   if (testPattern(wform.phone, phonereg) == false) isValid = false;

   creditType = wform.ccard.selectedIndex;
   switch (creditType) {
      case 0: cregx = /^3[47]\d{13}$/; break;
      case 1: cregx = /^30[0-5]\d{11}$|^3[68]\d{12}$/; break;
      case 2: cregx = /^6011\d{12}$/; break;
      case 3: cregx = /^5[1-5]\d{14}$/; break;
      case 4: cregx = /^4(\d{12}|\d{15})$/; break;
   }  

   if (testPattern(wform.cnum, cregx) == false) isValid = false;

   return isValid;
}


function testPattern(field, reg) {
   var isValid = true;

   wsregx = /\s/g;
   var fv =field.value.replace(wsregx,"");
   if (reg.test(fv) == false) {
      isValid = false;
      document.getElementById(input.id+"fname").style.bgcolor="yellow";
   } else {
      document.getElementById(input.id+"fname").style.bgcolor="white";
   }
   return isValid;
}

function validCNum() {
   var isValid = true;

   wsregx = /\s/g;
   var fv = wform.cnum.value.replace(wsregx,"");

   if (luhn(fv)==false) {
      isValid = false;
       document.getElementById("cnum").style.bgcolor="yellow";
   } else {
       document.getElementById("cnum").style.bgcolor="white";
   }

   return isValid;
}

 function changeColor(field) { 
var fv = field.value; 
if (fv.length==0) { 
field.style.background="yellow"; 
} else { 
field.style.background="white"; 
} 
} 
 


function validateForm() {

   var vLengths = validLengths();
   var vPatterns = validPatterns();
   var vCNum = validCNum();
   var vForm = vLengths && vPatterns && vCNum;
if (!vForm) {
      alert("Check the highlighted items in the form for missing/invalid data");
      return false;
   } else {
      return true;
   }
}
TheBewitching1 is offline   Reply With Quote
Old 05-01-2011, 05:55 PM   PM User | #2
ShaneC
Codeasaurus Rex


 
Join Date: Jun 2008
Location: Redmond, WA
Posts: 659
Thanks: 31
Thanked 100 Times in 94 Posts
ShaneC is on a distinguished road
Moved from Java to JavaScript
__________________
Unless otherwise stated, any code posted is most likely untested and may contain syntax errors.
My posts, comments, code, and suggestions reflect only my personal views.
Web Portfolio and Code Snippets: http://shanechism.com
ShaneC is offline   Reply With Quote
Old 05-01-2011, 08:41 PM   PM User | #3
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,168
Thanks: 59
Thanked 3,993 Times in 3,962 Posts
Old Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to all
Several things wrong.

Just for starters, you do this:
Code:
  if (testLength(wform.total)== false) isValid = false;
but that generates an error in testLength() because there is no element with the ID "totalcontact".

Why is your code looking for "totalcontact"??

Because you do this in testLength:
Code:
    document.getElementById(field.id+"contact").style.bgcolor= ...
So when you try to do testLength() of the total field, which has an id of "total", you try to set the background color of something with the id of "totalcontact".

And ditto for every field that you invoke testLength() on.

And similar for testPattern, where you do worse:
Code:
function testPattern(field, reg) {
   var isValid = true;

   wsregx = /\s/g;
   var fv =field.value.replace(wsregx,"");
   if (reg.test(fv) == false) {
      isValid = false;
      document.getElementById(input.id+"fname").style.bgcolor="yellow";
   } else {
      document.getElementById(input.id+"fname").style.bgcolor="white";
   }
   return isValid;
}
Here, you are trying to append "fname" to input.id. But input is not even a valid variable at this point in the code.

I'm *guessing* that you meant to use field.id, but that makes no sense, either, as you don't have any elements with an id of "xxxfname" except "fname" itself.

Quite frankly, I don't understand what the point of appending these strings to these ids is. Are you missing a bunch of tags that should, indeed, have ids such as "totalcontact" and "fnamecontact" and so on???
__________________
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.
Old Pedant is offline   Reply With Quote
Old 05-01-2011, 10:25 PM   PM User | #4
TheBewitching1
New to the CF scene

 
Join Date: May 2011
Posts: 2
Thanks: 0
Thanked 0 Times in 0 Posts
TheBewitching1 is an unknown quantity at this point
Yes I have a mess. I got totally lost trying to get the input fields to highlight when there was a validation error. I have no idea how to fix this where it will highlight if the input is missing and display and error message stating to check highlighted fields for missing input. If all fields are filled in correctly then it should go to the done page.
Thanks for your help
TheBewitching1 is offline   Reply With Quote
Old 05-01-2011, 11:48 PM   PM User | #5
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,168
Thanks: 59
Thanked 3,993 Times in 3,962 Posts
Old Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to all
You have another problem: Your action in your <form> is an HTML page and your method is post.

You can't post data to HTML pages; you can only post to server side pages (e.g, PHP/ASP/JSP/etc.).

You have to use get with HTML actions.

********

Further, and even more importantly, *ONLY* form fields that have *NAMES* will be sent by HTML processing to the next page.

Giving a form field a name is only helpful for using <label>s (and really isn't necessary, as I'll show you). The name is much much more important.
__________________
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.

Last edited by Old Pedant; 05-01-2011 at 11:52 PM..
Old Pedant is offline   Reply With Quote
Old 05-02-2011, 12:12 AM   PM User | #6
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,168
Thanks: 59
Thanked 3,993 Times in 3,962 Posts
Old Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to all
Here's an abbreviated, simplified, and corrected version of what I think you were after:
Code:
<html>
<head>
<script type="text/javascript">
function validateSelect(select)
{
    document.getElementById( select.name + "Lab" ).style.backgroundColor =
        ( select.selectedIndex == 0 ) ? "pink" : "transparent";
    return select.selectedIndex != 0;
}

function validateText(input)
{
    var text = input.value.replace(/\s/g,"");
    document.getElementById( input.name + "Lab" ).style.backgroundColor =
        ( text.length < 4 ) ? "pink" : "transparent";
    return text.length > 3;
}

function validateForm(form)
{
    var okay = validateSelect(form.product)
             & validateSelect(form.qty)
             & validateText(form.fname);
    if ( okay == 0 ) alert("Please correct the indicated errors");
    return okay != 0;
}
</script>
<body>
<form action="" onsubmit="return validateForm(this)" method="get">
<label id="productLab">1) Product
  <select name="product">
    <option value="">Select a Product</option>
    <option value="3.5">Green/Purple Fountain: $3.50 ea.</option>
    <option value="4.95">Silver Cone: $4.95 ea.</option>
    <option value="6.95">Glitter Cone: $6.95 ea.</option>
    <option value="9.95">Glittering Stars: $9.95 ea.</option>
    <option value="19.95">Fountain Kit: $19.95 ea.</option>
    <option value="29.95">Fountain Kit Deluxe: $29.95</option>
    <option value="39.95">Giant Fountain: $39.95</option>
  </select>
</label>
<br />
<label id="qtyLab">2) Quantity
  <select name="qty">
    <option value="">Select a Quantity</option>
    <option value="1"> 1</option>
    <option value="2"> 2</option>
    <option value="3"> 3</option>
    <option value="4"> 4</option>
    <option value="5"> 5</option>
    <option value="6"> 6</option>
    <option value="7"> 7</option>
    <option value="8"> 8</option>
    <option value="9"> 9</option>
    <option value="10">10</option>
  </select>  
</label>
<br/><br/>
<label id="fnameLab">4) First Name
  <input name="fname" size="20" type="text" />
</label>
<br/><br/>
<input type="submit" value="Submit Order" />
</form>

</body>
</html>
__________________
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.
Old Pedant is offline   Reply With Quote
Old 05-02-2011, 12:16 AM   PM User | #7
bullant
Banned

 
Join Date: Feb 2011
Posts: 2,699
Thanks: 13
Thanked 395 Times in 395 Posts
bullant is on a distinguished road
Quote:
Originally Posted by TheBewitching1 View Post
Yes I have a mess. I got totally lost trying to get the input fields to highlight when there was a validation error. I have no idea how to fix this.....
Maybe consider starting your javascript again incorporating some Basic Debugging 101 as you go along - basically, code and test in small chunks.
bullant is offline   Reply With Quote
Old 05-02-2011, 12:22 AM   PM User | #8
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,168
Thanks: 59
Thanked 3,993 Times in 3,962 Posts
Old Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to all
Here's another variation that simplifies the HTML even further: No id's needed for the <label>s. Flexibiity on minimum length for text fields.
Code:
<html>
<head>
<script type="text/javascript">
function colorLabel(field,okay)
{
    // find the label that contains the given field...
    var node = field.parentNode;
    while ( node.tagName.toLowerCase() != "label" )
    {
        node = node.parentNode;
        if ( node == null ) 
        {
           alert("Label not found for field " + field.name);
           return okay;
        }
    }
    // and set its color according to the flag
    node.style.backgroundColor = okay ? "transparent" : "pink";
    // and by returning the flag, we simplify the code in the callers
    return okay;
}

function validateSelect(select)
{
    return colorLabel(select, select.selectedIndex != 0);
}

function validateTextLength(input,min)
{
    var text = input.value.replace(/\s/g,"");
    return colorLabel( input, text.length >= min );
}

// notice how we passed the reference to the <form> object into this function:
function validateForm(form)
{
    // notice how we can so easily refer to the form fields by name:
    var okay = validateSelect(form.product)
             & validateSelect(form.qty)
             & validateTextLength(form.fname, 3);

    if ( okay == 0 ) alert("Please correct the indicated errors");
    return okay != 0;
}
</script>
<body>
<form action="" onsubmit="return validateForm(this)" method="get">
<label> 1) Product
  <select name="product">
    <option value="">Select a Product</option>
    <option value="3.5">Green/Purple Fountain: $3.50 ea.</option>
    <option value="4.95">Silver Cone: $4.95 ea.</option>
    <option value="6.95">Glitter Cone: $6.95 ea.</option>
    <option value="9.95">Glittering Stars: $9.95 ea.</option>
    <option value="19.95">Fountain Kit: $19.95 ea.</option>
    <option value="29.95">Fountain Kit Deluxe: $29.95</option>
    <option value="39.95">Giant Fountain: $39.95</option>
  </select>
</label>
<br />
<label> 2) Quantity
  <select name="qty">
    <option value="">Select a Quantity</option>
    <option value="1"> 1</option>
    <option value="2"> 2</option>
    <option value="3"> 3</option>
    <option value="4"> 4</option>
    <option value="5"> 5</option>
    <option value="6"> 6</option>
    <option value="7"> 7</option>
    <option value="8"> 8</option>
    <option value="9"> 9</option>
    <option value="10">10</option>
  </select>  
</label>
<br/><br/>
<label> 4) First Name
  <input name="fname" size="20" type="text" />
</label>
<br/><br/>
<input type="submit" value="Submit Order" />
</form>

</body>
</html>
__________________
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.

Last edited by Old Pedant; 05-02-2011 at 12:25 AM..
Old Pedant is offline   Reply With Quote
Old 01-27-2012, 05:45 AM   PM User | #9
thenm
New to the CF scene

 
Join Date: Jan 2012
Posts: 3
Thanks: 0
Thanked 0 Times in 0 Posts
thenm is an unknown quantity at this point
Jquery

Help with jquery validation:
How to validate a form usig tagname in jquery
my code is:
form.html
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="jquery.js" charset="utf-8"></script>
<script type="text/javascript" src="javasc.js" charset="utf-8"></script>

<link rel="stylesheet" href="style.css" type="text/css" media="screen" />
<script type="text/javascript">
//$(function() {
		 
		//var ele = $("input[type!='submit'], textarea, select");
		//ele.focus(function(){
		////	$(this).parents('p').addClass('block');
		//});
		//ele.blur(function(){
		//	$(this).parents('p').removeClass('block');
		//});
		
		
		
	//});
</script>
</head>
<body>

<div id="content">
	<form id="jform" action="# method="post">
		<fieldset>
			<legend>Personal Information</legend>
			<p>
				<label for="fullname" class="block"><h3>Name</h3></label>
				<input type="text" name="fullname" id="fullname" />
			</p>
            <p><h3>Email Address</h3>
				<label for="email" class="block"> <small>(mickey@mou.se)</small>:</label>
				<input type="text" name="email" id="email" />
			</p>
            <p>
				<label for="password" class="block"><h3>Password</h3></label>
				<input type="password" name="password" id="password" size="20"/>
			</p>
			<p>
				<label for="birthday" class="block"><h3>Day of birth </h3></label>
				<input type="text" name="birthday" id="birthday" /><small>(dd-mm-yyyy)</small>
                
			</p>
           <p>
				<label for="Phone" class="block"><h3>Phone </h3></label>
				<input type="text"  name="Phone" id="Phone" maxlength="10"  />
			</p>
			<p>
				<label class="block"><h3>I am:</h3></label>
				<input type="radio" name="gender" id="man" value="man" /> <label for="man">Male</label>
				<input type="radio" name="gender" id="woman" value="woman" /> <label for="woman">Female</label>
			</p>
		
		
			
		
			<h3>Address</h3>
			<p>
				<label for="about" class="block"></label>
				<textarea id="about" cols="30" rows="5"></textarea>
			</p>
            <p>
        <label for="category" class="block"><h3>Status </h3></label>
				<select name="category" id="category" /><option>  </option><option>Active</option><option>In-Active</option></select>
        </p>
        <p>
        <label for="type" class="block"><h3>Type </h3></label>
				<select name="type" id="type" /><option>  </option><option>Administrator</option><option>Sub-Administrator</option></select>
        </p>
	<p>
				<label class="block">Please agree:</label>
				
				<input type="checkbox" name="agree" id="ship" /> <label for="ship"></label>
			</p>

		</fieldset>
		<p>
			<button type="submit" id="send">submit</button>
		</p>
	</form>
</div>

</body>
</html>
--------------------------------------javasc.js is :
$(document).ready(function(){

	var jVal = {
		'fullName' : function() {

			$('body').append('<div id="nameInfo" class="info"></div>');

			var nameInfo = $('#nameInfo');
			var ele = $('#fullname');
			var pos = ele.offset();

			nameInfo.css({
				top: pos.top-3,
				left: pos.left+ele.width()+15
			});
           var patt = /^[A-Za-z]+$/;
			if(!patt.test(ele.val())) {
				jVal.errors = true;
					nameInfo.removeClass('correct').addClass('error').html('Enter Your Name	').show();
					ele.removeClass('normal').addClass('wrong');
			} else {
					nameInfo.removeClass('error').addClass('correct').html('&radic;').show();
					ele.removeClass('wrong').addClass('normal');
			}
		},
//-----------------------name validationend-------------------------------------------------------------------->
		'birthDate' : function (){

			$('body').append('<div id="birthInfo" class="info"></div>');

			var birthInfo = $('#birthInfo');
			var ele = $('#birthday');
			var pos = ele.offset();

			birthInfo.css({
				top: pos.top-3,
				left: pos.left+ele.width()+15
			});

			var patt = /^[0-9]{2}\-[0-9]{2}\-[0-9]{4}$/i;

			if(!patt.test(ele.val())) {
				jVal.errors = true;
					birthInfo.removeClass('correct').addClass('error').html(' type in date in correct format').show();
					ele.removeClass('normal').addClass('wrong');
			} else {
					birthInfo.removeClass('error').addClass('correct').html('&radic;').show();
					ele.removeClass('wrong').addClass('normal');
			}
		},
		
//-----------------------date validation-------------------------------------------------------------------->
		'gender' : function (){

			$('body').append('<div id="genderInfo" class="info"></div>');

			var genderInfo = $('#genderInfo');
			var ele = $('#woman');
			var pos = ele.offset();

			genderInfo.css({
				top: pos.top-10,
				left: pos.left+ele.width()+60
			});

			if($('input[name="gender"]:checked').length === 0) {
				jVal.errors = true;
					genderInfo.removeClass('correct').addClass('error').html('Enter Your Gender').show();//html('&larr; are you a man or a woman?').show();
					ele.removeClass('normal').addClass('wrong');
			} else {
					genderInfo.removeClass('error').addClass('correct').html('&radic;').show();
					ele.removeClass('wrong').addClass('normal');
			}
		},
//-----------------------gender validation end-------------------------------------------------------------------->
		'agree' : function (){

			$('body').append('<div id="agreeInfo" class="info"></div>');

			var agreeInfo = $('#agreeInfo');
			var ele = $('#ship');
			var pos = ele.offset();

			agreeInfo.css({
				top: pos.top-10,
				left: pos.left+ele.width()+40
			});

			if($('input[name="agree"]:checked').length <1) {
				jVal.errors = true;
					agreeInfo.removeClass('correct').addClass('error').html('Please agree the Policy ').show();
					ele.removeClass('normal').addClass('wrong');
			} else {
					agreeInfo.removeClass('error').addClass('correct').html('&radic;').show();
					ele.removeClass('wrong').addClass('normal');
			}
		},
//-----------------------agree validationend-------------------------------------------------------------------->
		'email' : function() {

			$('body').append('<div id="emailInfo" class="info"></div>');

			var emailInfo = $('#emailInfo');
			var ele = $('#email');
			var pos = ele.offset();

			emailInfo.css({
				top: pos.top-3,
				left: pos.left+ele.width()+15
			});

			var patt = /^.+@.+[.].{2,}$/i;

			if(!patt.test(ele.val())) {
				jVal.errors = true;
					emailInfo.removeClass('correct').addClass('error').html(' give me a valid email adress').show();
					ele.removeClass('normal').addClass('wrong');
			} else {
					emailInfo.removeClass('error').addClass('correct').html('&radic;').show();
					ele.removeClass('wrong').addClass('normal');
			}
		},
		//-----------------------email validationend-------------------------------------------------------------------->

		'password' : function() {

			$('body').append('<div id="passwordInfo" class="info"></div>');

			var passwordInfo = $('#passwordInfo');
			var ele = $('#password');
			var pos = ele.offset();

			passwordInfo.css({
				top: pos.top-3,
				left: pos.left+ele.width()+15
			});

			if(ele.val().length < 4) {
				jVal.errors = true;
					passwordInfo.removeClass('correct').addClass('error').html('Password length atleast 4').show();
					ele.removeClass('normal').addClass('wrong');
			} else {
					passwordInfo.removeClass('error').addClass('correct').html('&radic;').show();
					ele.removeClass('wrong').addClass('normal');
			}
		},
		
//----------------------password validationend-------------------------------------------------------------------->
	'about' : function() {

			$('body').append('<div id="aboutInfo" class="info"></div>');

			var aboutInfo = $('#aboutInfo');
			var ele = $('#about');
			var pos = ele.offset();

			aboutInfo.css({
				top: pos.top-3,
				left: pos.left+ele.width()+15
			});

			if(ele.val().length < 5) {
				jVal.errors = true;
					aboutInfo.removeClass('correct').addClass('error').html('Enter Address Details').show();
					ele.removeClass('normal').addClass('wrong').css({'font-weight': 'normal'});
			} else {
					aboutInfo.removeClass('error').addClass('correct').html('&radic;').show();
					ele.removeClass('wrong').addClass('normal');
			}
		},
		//-----------------------address validation end-------------------------------------------------------------------->

		
		'Phone' : function() {

			$('body').append('<div id="PhoneInfo" class="info"></div>');

			var PhoneInfo = $('#PhoneInfo');
			var ele = $('#Phone');
			var pos = ele.offset();

			PhoneInfo.css({
				top: pos.top-3,
				left: pos.left+ele.width()+15
			});

			if(ele.val().length < 10) {
				jVal.errors = true;
					PhoneInfo.removeClass('correct').addClass('error').html(' at least 10 characters').show();
					ele.removeClass('normal').addClass('wrong');
			} else {
					PhoneInfo.removeClass('error').addClass('correct').html('&radic;').show();
					ele.removeClass('wrong').addClass('normal');
			}
		},
		//-----------------------phone validation end-------------------------------------------------------------------->

'category' : function() {

			$('body').append('<div id="categoryInfo" class="info"></div>');

			var categoryInfo = $('#categoryInfo');
			var ele = $('#category');
			var pos = ele.offset();

			categoryInfo.css({
				top: pos.top-3,
				left: pos.left+ele.width()+15
			});

			if(ele.val().length <1) {
				jVal.errors = true;
					categoryInfo.removeClass('correct').addClass('error').html('select your Status').show();
					ele.removeClass('normal').addClass('wrong');
			} else {
					categoryInfo.removeClass('error').addClass('correct').html('&radic;').show();
					ele.removeClass('wrong').addClass('normal');
			}
		},
		//-----------------------Category validation end-------------------------------------------------------------------->

		'type' : function() {

			$('body').append('<div id="typeInfo" class="info"></div>');

			var typeInfo = $('#typeInfo');
			var ele = $('#type');
			var pos = ele.offset();

			typeInfo.css({
				top: pos.top-3,
				left: pos.left+ele.width()+15
			});

			if(ele.val().length <1) {
				jVal.errors = true;
					typeInfo.removeClass('correct').addClass('error').html('Select Your Type').show();
					ele.removeClass('normal').addClass('wrong');
			} else {
					typeInfo.removeClass('error').addClass('correct').html('&radic;').show();
					ele.removeClass('wrong').addClass('normal');
			}
		},
		
//-----------------------type validationend-------------------------------------------------------------------->
		'sendIt' : function (){
			if(!jVal.errors) {
				$('#jform').submit();
			}
		}
	};


	$('#send').click(function (){
		var obj = $.browser.webkit ? $('body') : $('html');
		obj.animate({ scrollTop: $('#jform') },  function (){
			jVal.errors = false;
			jVal.fullName();
			jVal.email();
			jVal.password();
			jVal.birthDate();
			jVal.Phone();
			jVal.gender();
			jVal.category();
			jVal.agree();
			jVal.type();
			jVal.about();
			jVal.sendIt();
		});
		return false;
	});

	$('#fullname').change(jVal.fullName);
	$('#birthday').change(jVal.birthDate);
	$('input[name="gender"]').change(jVal.gender);
	$('input[name="agree"]').change(jVal.agree);
	$('#email').change(jVal.email);
	$('#password').change(jVal.password);
	$('#Phone').change(jVal.Phone);
	$('#about').change(jVal.about);
	$('#type').change(jVal.type);
	$('#category').change(jVal.category);

});
//-----------------------Script validationend-------------------------------------------------------------------->
please give some idea

Last edited by WA; 01-27-2012 at 06:20 AM.. Reason: add coding
thenm is offline   Reply With Quote
Old 01-27-2012, 06:34 AM   PM User | #10
thenm
New to the CF scene

 
Join Date: Jan 2012
Posts: 3
Thanks: 0
Thanked 0 Times in 0 Posts
thenm is an unknown quantity at this point
how to validate a form in jquery using tag name


(ie)
$(function() {

var ele = $("input[type!='submit'], textarea, select");
ele.focus(function(){
$(this).parents('p').addClass('block');
});
ele.blur(function(){
$(this).parents('p').removeClass('block');
});



});

I have attached my code Here,Please check











<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="jquery.js" charset="utf-8"></script>
<script type="text/javascript" src="javasc.js" charset="utf-8"></script>

<link rel="stylesheet" href="style.css" type="text/css" media="screen" />
<script type="text/javascript">
//$(function() {

//var ele = $("input[type!='submit'], textarea, select");
//ele.focus(function(){
//// $(this).parents('p').addClass('block');
//});
//ele.blur(function(){
// $(this).parents('p').removeClass('block');
//});



//});
</script>
</head>
<body>

<div id="content">
<form id="jform" action="# method="post">
<fieldset>
<legend>Personal Information</legend>
<p>
<label for="fullname" class="block"><h3>Name</h3></label>
<input type="text" name="fullname" id="fullname" />
</p>
<p><h3>Email Address</h3>
<label for="email" class="block"> <small>(mickey@mou.se)</small>:</label>
<input type="text" name="email" id="email" />
</p>
<p>
<label for="password" class="block"><h3>Password</h3></label>
<input type="password" name="password" id="password" size="20"/>
</p>
<p>
<label for="birthday" class="block"><h3>Day of birth </h3></label>
<input type="text" name="birthday" id="birthday" /><small>(dd-mm-yyyy)</small>

</p>
<p>
<label for="Phone" class="block"><h3>Phone </h3></label>
<input type="text" name="Phone" id="Phone" maxlength="10" />
</p>
<p>
<label class="block"><h3>I am:</h3></label>
<input type="radio" name="gender" id="man" value="man" /> <label for="man">Male</label>
<input type="radio" name="gender" id="woman" value="woman" /> <label for="woman">Female</label>
</p>




<h3>Address</h3>
<p>
<label for="about" class="block"></label>
<textarea id="about" cols="30" rows="5"></textarea>
</p>
<p>
<label for="category" class="block"><h3>Status </h3></label>
<select name="category" id="category" /><option> </option><option>Active</option><option>In-Active</option></select>
</p>
<p>
<label for="type" class="block"><h3>Type </h3></label>
<select name="type" id="type" /><option> </option><option>Administrator</option><option>Sub-Administrator</option></select>
</p>
<p>
<label class="block">Please agree:</label>

<input type="checkbox" name="agree" id="ship" /> <label for="ship"></label>
</p>

</fieldset>
<p>
<button type="submit" id="send">submit</button>
</p>
</form>
</div>

</body>
</html>
--------------------------------------javasc.js is :
$(document).ready(function(){

var jVal = {
'fullName' : function() {

$('body').append('<div id="nameInfo" class="info"></div>');

var nameInfo = $('#nameInfo');
var ele = $('#fullname');
var pos = ele.offset();

nameInfo.css({
top: pos.top-3,
left: pos.left+ele.width()+15
});
var patt = /^[A-Za-z]+$/;
if(!patt.test(ele.val())) {
jVal.errors = true;
nameInfo.removeClass('correct').addClass('error').html('Enter Your Name ').show();
ele.removeClass('normal').addClass('wrong');
} else {
nameInfo.removeClass('error').addClass('correct').html('&radic;').show();
ele.removeClass('wrong').addClass('normal');
}
},
//-----------------------name validationend-------------------------------------------------------------------->
'birthDate' : function (){

$('body').append('<div id="birthInfo" class="info"></div>');

var birthInfo = $('#birthInfo');
var ele = $('#birthday');
var pos = ele.offset();

birthInfo.css({
top: pos.top-3,
left: pos.left+ele.width()+15
});

var patt = /^[0-9]{2}\-[0-9]{2}\-[0-9]{4}$/i;

if(!patt.test(ele.val())) {
jVal.errors = true;
birthInfo.removeClass('correct').addClass('error').html(' type in date in correct format').show();
ele.removeClass('normal').addClass('wrong');
} else {
birthInfo.removeClass('error').addClass('correct').html('&radic;').show();
ele.removeClass('wrong').addClass('normal');
}
},

//-----------------------date validation-------------------------------------------------------------------->
'gender' : function (){

$('body').append('<div id="genderInfo" class="info"></div>');

var genderInfo = $('#genderInfo');
var ele = $('#woman');
var pos = ele.offset();

genderInfo.css({
top: pos.top-10,
left: pos.left+ele.width()+60
});

if($('input[name="gender"]:checked').length === 0) {
jVal.errors = true;
genderInfo.removeClass('correct').addClass('error').html('Enter Your Gender').show();//html('&larr; are you a man or a woman?').show();
ele.removeClass('normal').addClass('wrong');
} else {
genderInfo.removeClass('error').addClass('correct').html('&radic;').show();
ele.removeClass('wrong').addClass('normal');
}
},
//-----------------------gender validation end-------------------------------------------------------------------->
'agree' : function (){

$('body').append('<div id="agreeInfo" class="info"></div>');

var agreeInfo = $('#agreeInfo');
var ele = $('#ship');
var pos = ele.offset();

agreeInfo.css({
top: pos.top-10,
left: pos.left+ele.width()+40
});

if($('input[name="agree"]:checked').length <1) {
jVal.errors = true;
agreeInfo.removeClass('correct').addClass('error').html('Please agree the Policy ').show();
ele.removeClass('normal').addClass('wrong');
} else {
agreeInfo.removeClass('error').addClass('correct').html('&radic;').show();
ele.removeClass('wrong').addClass('normal');
}
},
//-----------------------agree validationend-------------------------------------------------------------------->
'email' : function() {

$('body').append('<div id="emailInfo" class="info"></div>');

var emailInfo = $('#emailInfo');
var ele = $('#email');
var pos = ele.offset();

emailInfo.css({
top: pos.top-3,
left: pos.left+ele.width()+15
});

var patt = /^.+@.+[.].{2,}$/i;

if(!patt.test(ele.val())) {
jVal.errors = true;
emailInfo.removeClass('correct').addClass('error').html(' give me a valid email adress').show();
ele.removeClass('normal').addClass('wrong');
} else {
emailInfo.removeClass('error').addClass('correct').html('&radic;').show();
ele.removeClass('wrong').addClass('normal');
}
},
//-----------------------email validationend-------------------------------------------------------------------->

'password' : function() {

$('body').append('<div id="passwordInfo" class="info"></div>');

var passwordInfo = $('#passwordInfo');
var ele = $('#password');
var pos = ele.offset();

passwordInfo.css({
top: pos.top-3,
left: pos.left+ele.width()+15
});

if(ele.val().length < 4) {
jVal.errors = true;
passwordInfo.removeClass('correct').addClass('error').html('Password length atleast 4').show();
ele.removeClass('normal').addClass('wrong');
} else {
passwordInfo.removeClass('error').addClass('correct').html('&radic;').show();
ele.removeClass('wrong').addClass('normal');
}
},

//----------------------password validationend-------------------------------------------------------------------->
'about' : function() {

$('body').append('<div id="aboutInfo" class="info"></div>');

var aboutInfo = $('#aboutInfo');
var ele = $('#about');
var pos = ele.offset();

aboutInfo.css({
top: pos.top-3,
left: pos.left+ele.width()+15
});

if(ele.val().length < 5) {
jVal.errors = true;
aboutInfo.removeClass('correct').addClass('error').html('Enter Address Details').show();
ele.removeClass('normal').addClass('wrong').css({'font-weight': 'normal'});
} else {
aboutInfo.removeClass('error').addClass('correct').html('&radic;').show();
ele.removeClass('wrong').addClass('normal');
}
},
//-----------------------address validation end-------------------------------------------------------------------->


'Phone' : function() {

$('body').append('<div id="PhoneInfo" class="info"></div>');

var PhoneInfo = $('#PhoneInfo');
var ele = $('#Phone');
var pos = ele.offset();

PhoneInfo.css({
top: pos.top-3,
left: pos.left+ele.width()+15
});

if(ele.val().length < 10) {
jVal.errors = true;
PhoneInfo.removeClass('correct').addClass('error').html(' at least 10 characters').show();
ele.removeClass('normal').addClass('wrong');
} else {
PhoneInfo.removeClass('error').addClass('correct').html('&radic;').show();
ele.removeClass('wrong').addClass('normal');
}
},
//-----------------------phone validation end-------------------------------------------------------------------->

'category' : function() {

$('body').append('<div id="categoryInfo" class="info"></div>');

var categoryInfo = $('#categoryInfo');
var ele = $('#category');
var pos = ele.offset();

categoryInfo.css({
top: pos.top-3,
left: pos.left+ele.width()+15
});

if(ele.val().length <1) {
jVal.errors = true;
categoryInfo.removeClass('correct').addClass('error').html('select your Status').show();
ele.removeClass('normal').addClass('wrong');
} else {
categoryInfo.removeClass('error').addClass('correct').html('&radic;').show();
ele.removeClass('wrong').addClass('normal');
}
},
//-----------------------Category validation end-------------------------------------------------------------------->

'type' : function() {

$('body').append('<div id="typeInfo" class="info"></div>');

var typeInfo = $('#typeInfo');
var ele = $('#type');
var pos = ele.offset();

typeInfo.css({
top: pos.top-3,
left: pos.left+ele.width()+15
});

if(ele.val().length <1) {
jVal.errors = true;
typeInfo.removeClass('correct').addClass('error').html('Select Your Type').show();
ele.removeClass('normal').addClass('wrong');
} else {
typeInfo.removeClass('error').addClass('correct').html('&radic;').show();
ele.removeClass('wrong').addClass('normal');
}
},

//-----------------------type validationend-------------------------------------------------------------------->
'sendIt' : function (){
if(!jVal.errors) {
$('#jform').submit();
}
}
};


$('#send').click(function (){
var obj = $.browser.webkit ? $('body') : $('html');
obj.animate({ scrollTop: $('#jform') }, function (){
jVal.errors = false;
jVal.fullName();
jVal.email();
jVal.password();
jVal.birthDate();
jVal.Phone();
jVal.gender();
jVal.category();
jVal.agree();
jVal.type();
jVal.about();
jVal.sendIt();
});
return false;
});

$('#fullname').change(jVal.fullName);
$('#birthday').change(jVal.birthDate);
$('input[name="gender"]').change(jVal.gender);
$('input[name="agree"]').change(jVal.agree);
$('#email').change(jVal.email);
$('#password').change(jVal.password);
$('#Phone').change(jVal.Phone);
$('#about').change(jVal.about);
$('#type').change(jVal.type);
$('#category').change(jVal.category);

});
//-----------------------Script validationend-------------------------------------------------------------------->
thenm is offline   Reply With Quote
Old 01-27-2012, 07:32 AM   PM User | #11
Philip M
Supreme Master coder!

 
Philip M's Avatar
 
Join Date: Jun 2002
Location: London, England
Posts: 17,033
Thanks: 197
Thanked 2,410 Times in 2,388 Posts
Philip M has a spectacular aura aboutPhilip M has a spectacular aura aboutPhilip M has a spectacular aura about
thenm - Please do not hijack someone else's long-completed thread. Prefer to start a new thread of your own in the appropriate (jQuery) section of the forum. Please explain your problem clearly.

Before you do that, please read the forum rules and posting guidelines. When posting here please help us to help you by following the posting guidelines and wrapping your code in CODE tags. This means use the octothorpe or # button on the toolbar.

It is your responsibility to die() if necessary….. - PHP Manual
__________________

All the code given in this post has been tested and is intended to address the question asked.
Unless stated otherwise it is not just a demonstration.

Last edited by Philip M; 01-27-2012 at 07:36 AM..
Philip M is offline   Reply With Quote
Reply

Bookmarks

Tags
javascript, validation

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 01:11 AM.


Advertisement
Log in to turn off these ads.