Smart questions
Smart answers
Smart people
INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Member Login

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips now!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

Join Tek-Tips
*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

LINK TO THIS FORUM!

Add Stickiness To Your Site By Linking To This Professionally Managed Technical Forum.
Just copy and paste the
code below into your site.

Partner With Us!

"Best Of Breed" Forums Add Stickiness To Your Site
Partner Button
(Download This Button Today!)

Feedback

"...At last there is indeed a website/forum that deals with professional and serious matters. Keep up with the good work!!"

Geography

Where in the world do Tek-Tips members come from?

Java Script form validation code showing same errorHelpful Member! 

vishalonne (TechnicalUser)
30 Jul 12 5:10
Hi
I am trying to validate a form with different type of message for different error, but you can see Here the problem. Please guide me in solving this problem...
Partial Code of form.php-

CODE --> Script

<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Your Valuable Suggestion</title>
<link rel="stylesheet" type="text/css" href="view.css" media="all">
<script type="text/javascript">
function notEmpty(elem, helperMsg){
  if(elem.value.length == 0){
     document.getElementById('divforTextBox').innerHTML = helperMsg; 
     elem.focus();
     return false;
  }
  document.getElementById('divforTextBox').innerHTML = ""; 
  return true;
}
</script>
</head>
<body id="main_body" >
   <img id="top" src="top.png" alt="">
     <div id="form_container"
	<form id="form_453570" class="appnitro"  method="post" action="insertform.php">
	  <div class="form_description">
	     <h1>cbse cs n ip looks forward for your valuable suggestion</h1>
		<p>Please fill all the <font color="#EC0006">*</font> marked fields in CAPITAL letters. All <font color="#EC0006">*</font> marked fields are mandatory</div>						
		<ul >
		<li id="li_12" >
		<label class="description" for="element_12">First Name <font color="#EC0006">*</font> </label>
		<div>
		<input id="element_12" name="element_12" class="element text large" type="text" maxlength="255" value="" onblur="notEmpty(document.getElementById('element_12'), 'Please Enter Your First Name')"/> <div id='divforTextBox'></div>
		</div> 
		</li>		
                <li id="li_13" >
		<label class="description" for="element_13">Last Name <font color="#EC0006">*</font></label>
		<div>
		<input id="element_13" name="element_13" class="element text large" type="text" maxlength="255" value="" onblur="notEmpty(document.getElementById('element_12'), 'Please Enter Your Last Name')"/> <div id='divforTextBox'></div>
		</div> 
		</li>
<!-- Rest of the code -->
                <li id="li_11" >
		<li class="buttons">
                <input type="hidden" name="form_id" value="453570" />
		<input id="saveForm" class="button_text" type="submit" name="submit" value="Submit" />
		</li>
		</ul>
		</form>	
             <div id="footer"></div>
	</div>
	<img id="bottom" src="bottom.png" alt="">
	</body>
</html> 
feherke (Programmer)
30 Jul 12 5:47
Hi

First of all, ids must be unique. You have two divs with the id divforTextBox. That will cause problems. Anyway, you are kind of abusing the ids. In this case a class will be enough and the script can search for the first one following the input.

Regarding the validation, one way is to use regular expressions and store all the rules along the corresponding message in an object :

CODE --> JavaScript

var rule = {
  element_12: [
    [/^$/,       'Can not be empty'],
    [/^.$/,      'Must have at least 2 characters'],
    [/.{256,}/,  'Must have at most 255 characters'],
    [/\d/,       'Can not contain digits'],
  ],
  element_13: [
    [/^$/,       'Can not be empty'],
    [/^.{1,2}$/, 'Must have at least 3 characters'],
    [/.{256,}/,  'Must have at most 255 characters'],
  ],
}

function notEmpty(elem)
{
  var errorcontainer = elem;
  var result = true;

  do {
    errorcontainer = errorcontainer.nextSibling;
    if (errorcontainer == null) return result;
  } while (errorcontainer.className != 'errorcontainer');
  errorcontainer.innerHTML = '';

  if (! (elem.name in rule)) return result;

  for (var i = 0, l = rule[elem.name].length; i < l; i++) {
    if (elem.value.match(rule[elem.name][i][0])) {
      errorcontainer.innerHTML += rule[elem.name][i][1] + '<br>';
      result = false;
    }
  }

  return result;
} 

When calling it pass only a reference to the current element to notEmpty() :

CODE --> HTML

<li id="li_12" >
    <label class="description" for="element_12">First Name <font color="#EC0006">*</font> </label>
    <div>
    <input id="element_12" name="element_12" class="element text large" type="text" maxlength="255" value="" onblur="notEmpty(this)"/> <div class="errorcontainer"></div>
    </div> 
    </li>   
    <li id="li_13" >
    <label class="description" for="element_13">Last Name <font color="#EC0006">*</font></label>
    <div>
    <input id="element_13" name="element_13" class="element text large" type="text" maxlength="255" value="" onblur="notEmpty(this)"/> <div class="errorcontainer"></div>
    </div> 
    </li> 

Feherke.
http://feherke.github.com/

vishalonne (TechnicalUser)
30 Jul 12 6:19
Hi Feherke

You are again here to help. Thank you buddy...! I am done with the sample you mentioned. Its working What I have to do for validating radio button -

CODE --> HTML

<!-- ... -->
<li id="li_8" >
<label class="description" for="element_8">Stream <font color="#EC0006">*</font></label>
<span>
   <input id="element_8_1" name="element_8" class="element radio" type="radio" value="1" />
   <label class="choice" for="element_8_1">Humanities</label>
   <input id="element_8_2" name="element_8" class="element radio" type="radio" value="2" />
   <label class="choice" for="element_8_2">Commerce</label>
   <input id="element_8_3" name="element_8" class="element radio" type="radio" value="3" />
  <label class="choice" for="element_8_3">Science</label>
</span> 
</li>	
<!-- ... --> 
And corsor don't focus on the blank box it moves to next component.

feherke (Programmer)
30 Jul 12 7:29
Hi

Well, you should validate radio buttons separately. Their validation should be done per group, while the onblur event refers to one element.

Beside this, note that the user may directly click the submit button, in which case neither the text input validations will be triggered. ( Anyway, I hope you are validating the data on server side too, in your PHP script. )

So I would
  • Make another function to trigger all validations and call it onsubmit.
  • Make a dedicated function to check radio buttons.
  • Move the error container lookup in a separate function so can be used by the
radio button validator function too.

CODE --> JavaScript

function geterrorcontainer(elem)
{
  do {
    elem = elem.nextSibling;
  } while (elem != null && elem.className != 'errorcontainer');

  return elem;
}

function notEmpty(elem)
{
  if (! (elem.name in rule)) return result;

  var error = '';
  for (var i = 0, l = rule[elem.name].length; i < l; i++)
    if (elem.value.match(rule[elem.name][i][0]))
      error += rule[elem.name][i][1] + '<br>\n';

  geterrorcontainer(elem).innerHTML = error;
  if (error) elem.focus();

  return error == '';
}

function checkradio(form,name)
{
  var checked = false;
  for (var i = 0, l = form.elements[name].length; i < l; i++)
    if (form.elements[name][i].checked)
      checked = true;

  geterrorcontainer(form.elements[name][0]).innerHTML = checked ? '' : 'Must check one';
  if (!checked) form.elements[name][0].focus();

  return checked;
}

function checkform(form)
{
  return (
    checkradio(form,'element_11')
    & notEmpty(form.elements['element_13'])
    & notEmpty(form.element_12)
  ) != 0;
} 
Note that
  • Each validator function call will set the focus, so checkform() calls them in reverse order so at the end the focus remains on the first invalid input.
  • && short circuits the evaluation so only one invalid input would have its error message displayed.
  • & does not short circuit, but is arithmetic operator, so its result has to be transformed into boolean.

CODE --> (fragment)

<form id="form_453570" class="appnitro"  method="post" action="insertform.php" onsubmit="return checkform(this)">

<!-- ... -->

    <div>
      <input id="element_11_1" name="element_11" class="element radio" type="radio" value="1" />
      <label class="choice" for="element_11_1">Male</label>
      <input id="element_11_2" name="element_11" class="element radio" type="radio" value="2" />
      <label class="choice" for="element_11_2">Female</label>
      <div class="errorcontainer"></div>
    </div> 

If this validation Odyssey goes longer, would be better to search the web for a dedicated validator script. Preferably a HTML5 input attribute-based one, so if the browser is able to validate itself, to let be do it.

Feherke.
http://feherke.github.com/

vishalonne (TechnicalUser)
30 Jul 12 13:11
Hi Feherke...!
Finally I gave up and came with a very simple way to validate my form. When submit button is clicked at that time validation will start. But it Immediately goes to insertform.php after displaying the error message, you know this should not happen. It should stop...! Here is the code registration.js

CODE --> Script

function formValidation()
{
   var fn = document.registration.element_12;
   var ln = document.registration.element_13;
   var sx = document.registration.element_11;
   var em = document.registration.element_5;
   if(fname_validation(fn,5)){
     if(lname_validation(ln,5)){
       if(validsex(sx)){
         if(ValidateEmail(em)){
         }
       }
     }
   }
   return false;
} 
function fname_validation(fn,mx){
   var letters = /^[A-Za-z]+$/;
   var fn_len = fn.value.length;
   if (fn_len == 0 || fn_len < mx){
       document.getElementById('fnTextBox').innerHTML = "Enter your First name/ Minimum length is 5 characters ";
       fn.focus();
       if(fn.value.match(letters)){
	return true;
       }
       else{
	document.getElementById('fnTextBox').innerHTML = "Name must not contain other than alphabet";
	fn.focus();
	return false; //alert("User Id should not be empty / length be between "+mx+" to "+my);
       }
	return false;
   }
   return true;
}
function lname_validation(ln,mx){
   var letters = /^[A-Za-z]+$/;
   var ln_len = ln.value.length;
   if (ln_len == 0 || ln_len < mx){
       document.getElementById('lnTextBox').innerHTML = "Enter your Last name/ Minimum length is 5 characters ";
	   ln.focus();
	   if(ln.value.match(letters)){
	       return true;
	   }
	   else{
              document.getElementById('lnTextBox').innerHTML = "Name must not contain other than alphabet";
	     ln.focus();
	     return false; //alert("User Id should not be empty / length be between "+mx+" to "+my);
	   }
	   return false;
   }
   return true;
}
function validsex(sx){
  if(sx[0].checked != true || sx[1].checked != true){
      document.getElementById('sxRadio').innerHTML = "Select your Sex";
      sx.focus();
      return false;
  }
}
function ValidateEmail(em){
    var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
    if(em.value.match(mailformat)){
	return true;
    }
    else{
	document.getElementById('emTextBox').innerHTML = "Enter valid EMail ID";
	return false;
    }
} 

CODE --> HTML

This is form.php code-
<script src="registration.js"></script><ul>
<form id="form_453570" class="appnitro"  name="registration"  method="post" action="insertform.php" onSubmit="formValidation();"><li id="li_12" >
<label class="description" for="element_12">First Name <font color="#EC0006">*</font> </label>
<div> <input id="element_12" name="element_12" class="element text large" type="text" maxlength="255" value=""/>
<div id="fnTextBox"></div></div> 
 </li>
 <li id="li_13">
<label class="description" for="element_13">Last Name <font color="#EC0006">*</font></label>
<div> 
<input id="element_13" name="element_13" class="element text large" type="text" maxlength="255" value=""/> 
<div id="lnTextBox"></div></div> 
 </li>
<li id="li_11" >
<label class="description" for="element_11">Sex <font color="#EC0006">*</font></label>
<span>
<input id="element_11_1" name="element_11" class="element radio" type="radio" value="1" />
<label class="choice" for="element_11_1">Male</label>
<input id="element_11_2" name="element_11" class="element radio" type="radio" value="2" />
<label class="choice" for="element_11_2">Female</label>
</span> 
<div id="sxRadio"></div></li>
<li class="buttons">
	<input type="hidden" name="form_id" value="453570" />
	<input id="saveForm" class="button_text" type="submit" name="submit" value="Submit" />
	</li>
  </form> 

I request you please solve this issue.
feherke (Programmer)
30 Jul 12 13:20
Hi

Just compare the form tags :

CODE --> (fragment)

<!-- my -->
<form id="form_453570" class="appnitro"  method="post" action="insertform.php" onsubmit="return checkform(this)">

<!-- your -->
<form id="form_453570" class="appnitro"  name="registration"  method="post" action="insertform.php" onSubmit="formValidation();"> 

Feherke.
http://feherke.github.com/

vishalonne (TechnicalUser)
30 Jul 12 13:24
Thankyou you mean to say modified version of my code -

<form id="form_453570" class="appnitro" method="post" action="insertform.php" onsubmit="return formValidation(this)">
vishalonne (TechnicalUser)
30 Jul 12 13:27
Yes Yes it working But for Sex again moving on next page
feherke (Programmer)
30 Jul 12 13:49
Hi

Correct. Without the return keyword the value calculated in the event handler is not passed forward to the emitter.

The JavaScript equivalents of setting the event handler would look like this :

CODE --> JavaScript

// your earlier code - return value : undefined
document.getElementById('form_453570').onsubmit=function() { formValidation(this) }

// your latest code - return value : whatever formValidation() returns
document.getElementById('form_453570').onsubmit=function() { return formValidation(this) } 

Regarding the Sex validation, it passes because the JavaScript code throws a runtime error, so fails to the return the false value which would stop the submitting. The error is caused by the attempt to call the focus() method of the sx NodeList. Which does not exist. Change it to sx[0].focus();.

But your Sex validation condition says "if either male of female is unchecked, then scream". While is impossible to have both checked, the validation will always fail. Change it to if(!(sx[0].checked || sx[1].checked)){.

Feherke.
http://feherke.github.com/

vishalonne (TechnicalUser)
30 Jul 12 14:04
oooooofff.... at last doneglasses.
What is problem in ths code?

CODE --> Script

function ValidateEmail(em)
{
   var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
   if(em.value.match(mailformat))
   {
      return true;
   }
   else
   {
      document.getElementById('emTextBox').innerHTML = "Enter Valid EMail ID";
      return false;
   }
} 
<li id="li_5" >
<label class="description" for="element_5">Email <font color="#EC0006">*</font></label>
<div>
<input id="element_5" name="element_5" class="element text large" type="text" maxlength="255" value=""/>
<div id="emTextBox"></div>
</div>
</li>
It is again not checking the every thing is same as of first name and last name then why it is giving me pain?evil
vishalonne (TechnicalUser)
30 Jul 12 14:10
Okay Okay its Okay done..

I mention the nesting of this code
if(fname_validation(fn,5))
{
if(lname_validation(ln,5))
{
if(ValidateEmail(em))
{
if(validsex(sx))
{

}
}
}
}

with the sequence of the HTML element. Thank you Thank you Thank you Feherkewink
vishalonne (TechnicalUser)
30 Jul 12 15:00
Why Form is not not clearing the error if I enter the data after getting the error once. Let me explain -
Suppose I didn't fill up the email box,for which I got the error message and focus goes back to email text box. After that I fill it up properly and clicked on Submit button, but still it is showing the email error message not moving on next page.
Why So?
feherke (Programmer)
31 Jul 12 3:37
Hi

Quote (vishalonne)

still it is showing the email error message not moving on next page.
There are two separate things :
  • The error message does not disappear because nothing removes it. The cleanest way is to remove the message at the beginning of the function :

    CODE --> JavaScript

    function ValidateEmail(em){
      document.getElementById('emTextBox').innerHTML = '';
      var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
      if(em.value.match(mailformat)){
        return true;
      }
      else{
        document.getElementById('emTextBox').innerHTML = "Enter valid EMail ID";
        return false;
      }
    } 
  • The form is never submitted because the formValidation() function always returns false unconditionally. Just return true when all validation passed :

    CODE --> JavaScript

    function formValidation()
    {
      var fn = document.registration.element_12;
      var ln = document.registration.element_13;
      var sx = document.registration.element_11;
      var em = document.registration.element_5;
      if(fname_validation(fn,5)){
        if(lname_validation(ln,5)){
          if(validsex(sx)){
            if(ValidateEmail(em)){
              return true;
            }
          }
        }
      }
      return false;
    } 
This will still not work as there is something logically wrong in your functions. Usually is considered a bad idea to return on an if's both branches. Certainly having 2 ifs and 4 returns in a function ( talking about lname_validation() ) does not help understanding and/or debugging it.

Feherke.
http://feherke.github.com/

vishalonne (TechnicalUser)
31 Jul 12 5:12
What do you suggest? Feherke
vishalonne (TechnicalUser)
31 Jul 12 5:16
Can we use any sort of oblur event for clearing the message? I already used the second menthod in my code.
vishalonne (TechnicalUser)
31 Jul 12 5:17
And most important... how can validate 11 check box with current code?
vishalonne (TechnicalUser)
31 Jul 12 5:25
I am planning to do something like this, is this okay...

CODE --> Script

function validFeatures(f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11)
{
	x=0;
	if(f1.checked) || f2.checked || f3.checked) || f4.checked || f5.checked) || f6.checked || f7.checked) || f8.checked || f9.checked) || f10.checked || f11.checked)
	{
		x++;
	}
	if (x==1)
	{
		return true;
	}
	if(x==0)
	{
		document.getElementById('feCheck').innerHTML = "Select atleast 1 feature";
		f1.focus();
		return false;
	}
} 
Helpful Member!  feherke (Programmer)
31 Jul 12 5:58
Hi

Quote (vishalonne)

What do you suggest?
Well, I shown my suggested way earlier. And nothing seems to left from it.

Also gave a suggestion for further development : use HTML5 with a script which adds validation for older browsers. For example h5Validate. ( Not used it myself. Mentioned it just as an example. )

Quote (vishalonne)

Can we use any sort of oblur event for clearing the message?
Yes. Uncomfortable to code it as you will have to mention all those ids in yet another place. I shown my suggested way to avoid using so many ids and simplify the code earlier. And nothing seems to left from it.

Quote (vishalonne)

And most important... how can validate 11 check box with current code?
With the current code hardly. But could be easily solved with the checkradio() I posted earlier. And nothing seems to left from it.

Quote (vishalonne)

I am planning to do something like this, is this okay...
Ugly and hard to maintain, but would work if your closing parenthesis ( ) ) in the if condition would match up.

Feherke.
http://feherke.github.com/

vishalonne (TechnicalUser)
31 Jul 12 6:13
Thanks Feherke.. really I am thankful to you... but really I am not aware of HTML5 can you suggest me some some online resource or site where I can find material to learn and develop
feherke (Programmer)
31 Jul 12 6:30
Hi

There are plenty of such materials. Some of them I find useful :

Feherke.
http://feherke.github.com/

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members!

Back To Forum

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close