Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 13 of 13
  1. #1
    Regular Coder oVTech's Avatar
    Join Date
    Nov 2010
    Location
    USA
    Posts
    296
    Thanks
    4
    Thanked 54 Times in 52 Posts

    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.

  • #2
    Supreme Master coder! glenngv's Avatar
    Join Date
    Jun 2002
    Location
    Philippines
    Posts
    11,037
    Thanks
    0
    Thanked 250 Times in 246 Posts
    #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>

  • Users who have thanked glenngv for this post:

    oVTech (11-03-2010)

  • #3
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,918
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    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.

  • Users who have thanked Philip M for this post:

    oVTech (11-03-2010)

  • #4
    Regular Coder oVTech's Avatar
    Join Date
    Nov 2010
    Location
    USA
    Posts
    296
    Thanks
    4
    Thanked 54 Times in 52 Posts
    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.

  • #5
    Regular Coder oVTech's Avatar
    Join Date
    Nov 2010
    Location
    USA
    Posts
    296
    Thanks
    4
    Thanked 54 Times in 52 Posts
    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!

  • #6
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,918
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    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).

  • Users who have thanked Philip M for this post:

    oVTech (11-03-2010)

  • #7
    Regular Coder oVTech's Avatar
    Join Date
    Nov 2010
    Location
    USA
    Posts
    296
    Thanks
    4
    Thanked 54 Times in 52 Posts
    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!

  • #8
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,918
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    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;
    }

  • #9
    Regular Coder oVTech's Avatar
    Join Date
    Nov 2010
    Location
    USA
    Posts
    296
    Thanks
    4
    Thanked 54 Times in 52 Posts
    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!

  • #10
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,918
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    How are you calling your validation function?

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

  • #11
    Regular Coder oVTech's Avatar
    Join Date
    Nov 2010
    Location
    USA
    Posts
    296
    Thanks
    4
    Thanked 54 Times in 52 Posts
    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.

  • #12
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,918
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    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.

  • #13
    Regular Coder oVTech's Avatar
    Join Date
    Nov 2010
    Location
    USA
    Posts
    296
    Thanks
    4
    Thanked 54 Times in 52 Posts
    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>


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •