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 11-03-2010, 07:17 AM   PM User | #1
oVTech
Regular Coder

 
oVTech's Avatar
 
Join Date: Nov 2010
Location: USA
Posts: 296
Thanks: 4
Thanked 54 Times in 52 Posts
oVTech is an unknown quantity at this point
Exclamation JS Form Validation Issues

Hello guys,

I am trying to create a basic unobtrusive form validation function but I am having some issues/questions. Basically I am checking if any of the form fields have <= 3 characters, and if they do so, then I make those fields' backgrounds and borders red. Also in the empty <span> tags I insert an error message. My issues/questions are:

#1: So when I say if (fieldVals[i]<=3) this means that the errors should appear if the values are 1,2 or 3 characters long, right? It does not do that though, when I insert one character in any of the form fields the errors go away, but they should not, right?

#2: How do I cancel the form from submitting if errors are visible and vice versa? When I use the return false when errors are visible, the code does not even run. What is going on? return true does the same.

#3: When I use a submit button(type="submit") instead of just a button(type="button"), the code does not run? What am I doing wrong?

NOTE: I am not trying to use this on a website, I am just trying to learn how to use unobtrusive javascript. That's why I am only checking for empty fields. If I learn how to do this first, later I will try to add email check, date check etc.

(sorry for the long message)
Any help would be much appreciated, thanks!


THE CODE:

function addEvent (eventObj, event, codeToEexcute) {
if (eventObj.addEventListener) { eventObj.addEventListener(event, codeToEexcute, false );
}
else if (eventObj.attachEvent) { // If IE
event = "on" + event; eventObj.attachEvent(event, codeToEexcute);
}
}


function cancelEvent(event) {
if (event.preventDefault) {
event.preventDefault();
event.stopPropagation();
}
else {
event.returnValue = false;
event.cancelBubble = true;
}
}


addEvent(window, 'load', pageEvents);

function pageEvents () {
if (!document.getElementById || !document.createTextNode) {return;}
var send = document.getElementById('send');//<input type="button" id="send" value="Contact Us" />
if (!send) {return;}
addEvent(send, 'click', validate);
}



function validate () {
var name = document.getElementById('name'); //<input type="text" name="name" id="name" value="" />
var lastName = document.getElementById('lastName'); //<input type="text" name="lastName" id="lastName" value="" />
var email = document.getElementById('email'); //<input type="text" name="email" id="email" value="" />
var subject = document.getElementById('subject'); //<input type="text" name="subject" id="subject" value="" />
var message = document.getElementById('message'); //<textarea name="message" id="message" value=""></textarea>

var fields = [name, lastName, email, subject, message];
var fieldVals = [name.value, lastName.value, email.value, subject.value, message.value];

for (var i = 0; i<fieldVals.length; i++) {

var contactForm = document.getElementById('contactForm'); //<form> tag
var errs = contactForm.getElementsByTagName('span'); //one empty <span> tag next to each form field

if (fieldVals[i]<=3) { //BUG HERE: it still validates with 3 or less character but it should not, right?
fields[i].style.background = "#FFCCCC";
fields[i].style.borderColor = "red";
errs[i].innerHTML ="Please enter a correct value"; //by using 'i' I get the same index for the <span> tags
//if I insert a "return false" here, the code above does not run.
//how do I make the form not to submit when the code above is executed?
}
else {
fields[i].style.background = "none";
fields[i].style.borderColor = "#cecece";
errs[i].innerHTML = " ";
//how do I make the form to submit? when i use "return true" the code above does not run.
}
}//end for loop
}//end validate


Last edited by oVTech; 11-03-2010 at 07:32 AM..
oVTech is offline   Reply With Quote
Old 11-03-2010, 07:45 AM   PM User | #2
glenngv
Supreme Master coder!


 
glenngv's Avatar
 
Join Date: Jun 2002
Location: Los Angeles, CA Original Location: Philippines
Posts: 10,241
Thanks: 0
Thanked 112 Times in 111 Posts
glenngv will become famous soon enough
#1
Code:
if (fieldVals[i].length<=3)
#2. Have a boolean flag that is set to true by default. If an input is invalid, set it to false. Then at the end of the function return this flag.
Code:
   ...
   var valid=true;
   if (fieldVals[i].length<=3) {
      valid=false;
       ... 
   }
   else {
       ...
   }
 }//end outer for loop

  return valid;

}//end validate
#3 Use submit button and then call validate() on form onsubmit, no onclick on the submit button
Code:
<form onsubmit="return validate();">
...
<input type="submit" value="Submit" />
</form>
__________________
Glenn
_____________________________________________
Play Tower of Hanoi Android app (Ad-FREE!)
Play Tower of Hanoi Android app (FREE!)
Go to Tower of Hanoi Leaderboard
Play Tower of Hanoi Facebook app

Last edited by glenngv; 11-03-2010 at 07:47 AM..
glenngv is offline   Reply With Quote
Users who have thanked glenngv for this post:
oVTech (11-03-2010)
Old 11-03-2010, 08:38 AM   PM User | #3
Philip M
Supreme Master coder!

 
Philip M's Avatar
 
Join Date: Jun 2002
Location: London, England
Posts: 17,044
Thanks: 197
Thanked 2,412 Times in 2,390 Posts
Philip M has a spectacular aura aboutPhilip M has a spectacular aura aboutPhilip M has a spectacular aura about
What if the user enters three spaces or ??? into the field?

var send = document.getElementById('send')
var name = document.getElementById('name');
var subject = document.getElementById('subject');

It is advised that you do not use exactly the same name for a JavaScript variable and an HTML element. This will cause the script to fail in IE if you omit the var keyword (i.e. give the variable global scope).

Last edited by Philip M; 11-03-2010 at 08:44 AM..
Philip M is offline   Reply With Quote
Users who have thanked Philip M for this post:
oVTech (11-03-2010)
Old 11-03-2010, 05:18 PM   PM User | #4
oVTech
Regular Coder

 
oVTech's Avatar
 
Join Date: Nov 2010
Location: USA
Posts: 296
Thanks: 4
Thanked 54 Times in 52 Posts
oVTech is an unknown quantity at this point
Philip M,

Thank you for pointing out that IE will give an error if global variables have the same name as HTML elements (I did not know that). In terms of what happens if the user enters three spaces - if the user enters three spaces, the validation will fail because I am testing for less than or three. But your logic is correct. If the user enters four spaces our four characters such as "****", then the validation will pass. Perhaps there are Regular Expressions for matching white spaces and other characters (I will look into it). Thank you for point them out, I appreciate it.
oVTech is offline   Reply With Quote
Old 11-03-2010, 05:45 PM   PM User | #5
oVTech
Regular Coder

 
oVTech's Avatar
 
Join Date: Nov 2010
Location: USA
Posts: 296
Thanks: 4
Thanked 54 Times in 52 Posts
oVTech is an unknown quantity at this point
Glenn,

It was silly of me to forget the length property, thank you for catching that. The boolean flag method is awesome and it makes sense. I added the return validate() on the form tag and it works fine. The thing is that I am trying to validate through only JS code and did not want to have to go into the form tag and add an onsubmit event-handler, although it works fine. I think there is a way of validating through only JS code, but I am not sure how. I tried to use my addEven() like this instead:

var contactForm = document.getElementById('contactForm');
addEvent(contactForm, 'submit', validate);


It did not work though... And when I tried to add this:

var contactForm = document.getElementById('contactForm');
addEvent(contactForm, 'submit', return validate);


It gave me a syntax error. I will look more into it, but if you have any suggestions, please let me know. Thank you for your help!
oVTech is offline   Reply With Quote
Old 11-03-2010, 06:13 PM   PM User | #6
Philip M
Supreme Master coder!

 
Philip M's Avatar
 
Join Date: Jun 2002
Location: London, England
Posts: 17,044
Thanks: 197
Thanked 2,412 Times in 2,390 Posts
Philip M has a spectacular aura aboutPhilip M has a spectacular aura aboutPhilip M has a spectacular aura about
Code:
x = x.replace(/^\s+|\s+$/g,"");  // strip leading and trailing spaces

x = x.replace(/[^a-z\s\-\']/gi,"");  strip anything except letters spaces hyphen apostrophe  (name can be Riley-O'Flanagan).
Philip M is offline   Reply With Quote
Users who have thanked Philip M for this post:
oVTech (11-03-2010)
Old 11-03-2010, 06:47 PM   PM User | #7
oVTech
Regular Coder

 
oVTech's Avatar
 
Join Date: Nov 2010
Location: USA
Posts: 296
Thanks: 4
Thanked 54 Times in 52 Posts
oVTech is an unknown quantity at this point
Philip M,

Thank you for that, it will be very useful.
My validation is almost ready, but I encountered another issue. This is what happens: When I leave everything empty the errors appear (great!), when I fill in all values except some values of text boxes, the errors for those text boxes appear just fine (great!), but when I leave all the text boxes empty and I only fill in the textarea(var message), the form validates anyway. I think it has do with the array fields[i] and the fact that arrays start with 0. I am not sure how to add 1 to the array and at the same time test it. I tried something like this but no luck:

var valid = true;
var emptyFields = fieldVals[i].length<=3;

if (emptyFields) {
(fields[i] +1).style.background="#FFCCCC";
(fields[i] +1).style.borderColor = "red";
errs[i].innerHTML = "Please enter a correct value";
valid = false;
}


Any suggestions? Thanks!
oVTech is offline   Reply With Quote
Old 11-03-2010, 06:50 PM   PM User | #8
Philip M
Supreme Master coder!

 
Philip M's Avatar
 
Join Date: Jun 2002
Location: London, England
Posts: 17,044
Thanks: 197
Thanked 2,412 Times in 2,390 Posts
Philip M has a spectacular aura aboutPhilip M has a spectacular aura aboutPhilip M has a spectacular aura about
Code:
if (emptyFields) {
fields[i+1].style.background="#FFCCCC";
fields[i+1].style.borderColor = "red";
errs[i].innerHTML = "Please enter a correct value";
valid = false;
}
Philip M is offline   Reply With Quote
Old 11-03-2010, 07:09 PM   PM User | #9
oVTech
Regular Coder

 
oVTech's Avatar
 
Join Date: Nov 2010
Location: USA
Posts: 296
Thanks: 4
Thanked 54 Times in 52 Posts
oVTech is an unknown quantity at this point
Philip M,

Unfortunately it did not work , as soon as I press the submit button it validates and it does not display any errors. I am not sure why that happens . I guess JS is really kicking me in the head! Any other suggestions would be much appreciated!

Thanks!
oVTech is offline   Reply With Quote
Old 11-03-2010, 07:12 PM   PM User | #10
Philip M
Supreme Master coder!

 
Philip M's Avatar
 
Join Date: Jun 2002
Location: London, England
Posts: 17,044
Thanks: 197
Thanked 2,412 Times in 2,390 Posts
Philip M has a spectacular aura aboutPhilip M has a spectacular aura aboutPhilip M has a spectacular aura about
How are you calling your validation function?

<form ........ onsubmit = "return validate()">
Philip M is offline   Reply With Quote
Old 11-03-2010, 07:13 PM   PM User | #11
oVTech
Regular Coder

 
oVTech's Avatar
 
Join Date: Nov 2010
Location: USA
Posts: 296
Thanks: 4
Thanked 54 Times in 52 Posts
oVTech is an unknown quantity at this point
Yes I am calling it like this.

<form ........ onsubmit = "return validate()">

Any suggestions?
Thanks!

Last edited by oVTech; 11-03-2010 at 07:31 PM..
oVTech is offline   Reply With Quote
Old 11-03-2010, 07:42 PM   PM User | #12
Philip M
Supreme Master coder!

 
Philip M's Avatar
 
Join Date: Jun 2002
Location: London, England
Posts: 17,044
Thanks: 197
Thanked 2,412 Times in 2,390 Posts
Philip M has a spectacular aura aboutPhilip M has a spectacular aura aboutPhilip M has a spectacular aura about
You seem to have introduced a variable named valid. So in the script you must put

return valid;

with valid being set to boolean true or false according to the validation.

The best way to test is to strip it down to one or two fields only, then add more fields as you find that the script works successfully.
Philip M is offline   Reply With Quote
Old 11-03-2010, 08:06 PM   PM User | #13
oVTech
Regular Coder

 
oVTech's Avatar
 
Join Date: Nov 2010
Location: USA
Posts: 296
Thanks: 4
Thanked 54 Times in 52 Posts
oVTech is an unknown quantity at this point
Yes that is definitely a good thing to do. I'll keep that in mind!

Well here is the whole page for anyone that might be able to help! Thanks!


JAVASCRIPT:
Code:

		function validate () {
			var name = document.getElementById('name'); 
			var lastName = document.getElementById('lastName'); 
			var email = document.getElementById('email'); 
			var subject = document.getElementById('subject'); 
			var message = document.getElementById('message'); 
			
			var fields = [name, lastName, email, subject, message];
			var fieldVals = [name.value, lastName.value, email.value, subject.value, message.value];

			for (var i = 0; i<fieldVals.length; i++) {
				var contactForm = document.getElementById('contactForm'); 
				var errs = contactForm.getElementsByTagName('span'); 
						var valid = true;
						var emptyFields = fieldVals[i].length<=3;
						if (emptyFields) {
								fields[i].style.background = "#FFCCCC";
								fields[i].style.borderColor = "red";
								errs[i].innerHTML = "Please enter a correct value";
								valid = false;
						} 
						else {
							fields[i].style.background = "none";
							fields[i].style.borderColor = "#cecece";
							errs[i].innerHTML = " ";
							valid = true;
						}
			}//end for loop
			return valid;
		}//end validate


HTML:
Code:
	<form name="contactForm" id="contactForm" action="" target="" onsubmit="return validate()">
		<label for="name"><strong> name: </strong></label> <br />
		<input type="text" name="name" id="name" value="" /> <span class="err"></span> <br /> <br />
		
		<label for="lastName"><strong> last-name </strong></label> <br />
		<input type="text" name="lastName" id="lastName" value="" /> <span class="err"></span> <br /> <br />
		
		<label for="email"><strong> email: </strong></label> <br />
		<input type="text" name="email" id="email" value="" /> <span class="err"></span> <br /> <br />
		
		<label for="subject"><strong> subject: </strong></label> <br />
		<input type="text" name="subject" id="subject" value="" /> <span class="err"></span> <br /> <br />
		
		<label for="message"><strong> message: </strong></label> <br />
		<textarea name="message" id="message" value="" rows="12" cols="42"></textarea> <span class="err"></span>
		
		<br /> <br />
		<input type="submit"  id ="send" value="Submit" />
	</form>
oVTech is offline   Reply With Quote
Reply

Bookmarks

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 07:36 PM.


Advertisement
Log in to turn off these ads.