www.webdeveloper.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 23

Thread: JavaScript/JQuery Form Validation Help

  1. #1
    Join Date
    Jul 2014
    Posts
    15

    JavaScript/JQuery Form Validation Help

    Hi everyone -

    I'm tasked to build validation for an HTML form using JavaScript. I've never actually done JavaScript form validation so this is a pretty new area for me and the tutorials I've found have been a bit helpful but I haven't found scenarios for these types of validation:

    - Make sure the first name and last name fields aren't empty. Before sending the names to the server, process them so that they would have the first capital letter and all the remaining letters are small.
    - Check that the State field contains two capital letters.
    - Make sure ZIP code field is positive number.
    - Check that a value is selected in a list of check boxes.
    - Check for a valid date in the date field.
    - Check that something is selected in the radio button selection.

    Sorry for all of the unique scenarios, going crazy trying to figure these out. If any one can recommend how to go about creating the above validations or useful spots to check I'd appreciate it.

    (The university is teaching extremely dates and poor habits for JavaScript validation I've been told so I'm hoping to get a better understanding...)

    Thanks guys

  2. #2
    Join Date
    Oct 2013
    Posts
    490
    Have you built the form?
    Have you made an attempt at the scripting?
    Have you failed in either?

    Failure is a great teacher. Apparently better than the 'professor' you have.

    That out of the way:
    Point 1: CSS text transform and if (blah.value == ''){do something}
    Point 2: <select>
    Point 3: Too easy to check if less than zero [if (blah.value<'0'){do something}] although why anyone would put a '-' in front of a zip code is beyond me...
    Point 4: if ((blah.value == '') && (blah1.value == '') && ([etc.])){do something}
    Point 5: <input type="date"> (HTML5 form attribute)
    Point 6: <input type="radio" required>

    Now, those are real-world solutions if I were to make the form. Probably won't pass the assignment.

    I always like to build code that's beyond what a homework poster should know so that if it's submitted the teacher/professor can tell the student, "We never covered _______ in this class. How do you know how to do that? You cheated and get a 0 for this assignment." OK, it's a bit of evil pleasure.

    But seriously, it's to your advantage to at least try. If you really have problems with something post your code here and someone will jump on it and help you. Otherwise you may not get much more help than the hints I've already given.
    Last edited by Kevin2; 07-27-2014 at 01:35 AM.

  3. #3
    Join Date
    Mar 2012
    Posts
    1,560
    I know that you have to do the assignment as set, but really validating client-side is too insecure. You are going to need to re-validate server-side anyway. So it is just duplicating work, and introducing the possibility of discrepancies between the validation done client and server side, which can be a pain to spot. Against that, if your server is steam-driven, then you might prefer not to submit the form until validated, but I think that is the wrong solution. I suggest that your prof might consider posing a better example? One that is actually useful!

  4. #4
    Join Date
    Feb 2013
    Posts
    92
    Quote Originally Posted by jedaisoul View Post
    I know that you have to do the assignment as set, but really validating client-side is too insecure. You are going to need to re-validate server-side anyway. So it is just duplicating work, and introducing the possibility of discrepancies between the validation done client and server side, which can be a pain to spot. Against that, if your server is steam-driven, then you might prefer not to submit the form until validated, but I think that is the wrong solution. I suggest that your prof might consider posing a better example? One that is actually useful!
    I disagree, you can validate a lot of input fields before going to the server and I don't see what is so insecure in making sure a field is filled out correctly or at all. Checking data to make sure it's valid can be easily done in JavaScript or JQuery and other input fields of that nature. This way the user doesn't have to wait for a server response or have the page reload and before you say what about people who have JavaScript turned off? Simple, it still can be done server-side, but with graceful degradation. I would guess 90-95 percent have JavaScript enable, so that is a mute point. Sure there are input fields that need to be done on the server side, for example checking to make sure a username isn't already being used in a login module that comes to top of my mind. Or even checking a password, you would definitely want that done on the server-side.
    Last edited by Strider64; 07-27-2014 at 07:55 AM.

  5. #5
    Join Date
    Apr 2014
    Posts
    4
    Quote Originally Posted by Strider64 View Post
    I disagree, you can validate a lot of input fields before going to the server and I don't see what is so insecure in making sure a field is filled out correctly or at all. Checking data to make sure it's valid can be easily done in JavaScript or JQuery and other input fields of that nature. This way the user doesn't have to wait for a server response or have the page reload and before you say what about people who have JavaScript turned off? Simple, it still can be done server-side, but with graceful degradation. I would guess 90-95 percent have JavaScript enable, so that is a mute point. Sure there are input fields that need to be done on the server side, for example checking to make sure a username isn't already being used in a login module that comes to top of my mind. Or even checking a password, you would definitely want that done on the server-side.
    I totally agree with Strider here.

    I practice client side validation as an enhancement rather than a reliable function given that, as previously mentioned, it is very easy to disable Javascript or bypass client side validation.

    Forms should definitely be validated server side but client side is a great addition for so many reasons, for example;

    • User experience - instant inline validation help seems much more desirable than filling out a form, hitting submit, then waiting to be told what's wrong
    • Server load - could aid filtering our so many redundant requests to your server

  6. #6
    Join Date
    Jul 2014
    Posts
    15
    @ Kevin2
    Thanks for the reply Kevin!

    Yes I already have the form made, I wasn't sure if that was beneficial to include in this or not. I'll edit this in a bit and include my code.

    Yes I have made an attempt at the scripting for parts of the validation; some of the easier validations worked such as "checking if it's empty". But I got stuck on the ones I included.

    Form, no, I've made forms in the past and I'm sure there's modifications to clean my form up though. Scripting, absolutely, learned from a few mistakes as well.

    I totally appreciate the information and I wasn't looking for someone to do the assignment, just would like to understand the material more since I know I'll need the understanding and learning for future assignments, so I don't blame you one bit
    Last edited by jedaisoul; 07-28-2014 at 03:10 AM. Reason: lengthy quote deleted

  7. #7
    Join Date
    Jul 2014
    Posts
    15
    Here's the script and HTML. I'm doing something wrong with the portion of the Script for the ZIP code since my validations stopped working at this point (I decided to attempt a parseint for the ZIP code):


    Code:
    <script>
    function validateForm() {
        var x = document.forms["register-form"]["firstname"].value;
        if (x == null || x == "") {
            alert("First name must be filled out");
            return false;
        }
        var x = document.forms["register-form"]["lastname"].value;
        if (x == null || x == "") {
            alert("Last name must be filled out");
            return false;
        }
        var x = document.forms["register-form"]["address1"].value;
        if (x == null || x == "") {
            alert("Address Line 1 must be filled in.");
            return false;
        }
        var x = document.forms["register-form"]["city"].value;
        if (x == null || x == "") {
            alert("City must be filled in.");
            return false;
        }
        var x = document.forms["register-form"]["zip"].value;
        if(parseInt(document.getElementById("zip").value) < 0)
            alert("Number is not positive");
            return false;
        }
    }
    </script>
    Code:
    <form action="" id="register-form" name="register-form" onsubmit="return validateForm()" method="post">
    First name: <input type="text" name="firstname"><br />
    Last name: <input type="text" name="lastname"><br />
    Address Line 1: <input type="text" name="address1"><br />
    Address Line 2: <input type="text" name="address2"><br />
    City: <input type="text" name="city"><br />
    State: <select>
      <option value="Alabama">AL</option>
      <option value="Alaska">AK</option>
      <option value="Arizona">AZ</option>
      <option value="Arkansas">AR</option>
      <option value="California">CA</option>
      <option value="Colorado">CO</option>
      <option value="Conneticut">CT</option>
      <option value="Delaware">DE</option>
      <option value="Florida">FL</option>
      <option value="Georgia">GA</option>
      <option value="Hawaii">HI</option>
      <option value="Idaho">ID</option>
      <option value="Illinois">IL</option>
      <option value="Indiana">IN</option>
      <option value="Iowa">IA</option>
      <option value="Kansas">KS</option>
      <option value="Kentucky">KY</option>
      <option value="Louisiana">LA</option>
      <option value="Maine">ME</option>
      <option value="Maryland">MD</option>
      <option value="Massachusetts">MA</option>
      <option value="Michigan">MI</option>
      <option value="Minnesota">MN</option>
      <option value="Mississippi">MS</option>
      <option value="Missouri">MO</option>
      <option value="Montana">MT</option>
      <option value="Nebraska">NE</option>
      <option value="Nevada">NV</option>
      <option value="New Hampshire">NH</option>
      <option value="New Jersey">NJ</option>
      <option value="New Mexico">NM</option>
      <option value="New York">NY</option>
      <option value="North Carolina">NC</option>
      <option value="North Dakota">ND</option>
      <option value="Ohio">OH</option>
      <option value="Oklahoma">OK</option>
      <option value="Oregon">OR</option>
      <option value="Pennsylvania">PA</option>
      <option value="Rhode Island">RI</option>
      <option value="South Carolina">SC</option>
      <option value="South Dakota">SD</option>
      <option value="Tennessee">TN</option>
      <option value="Texas">TX</option>
      <option value="Utah">UT</option>
      <option value="Vermont">VT</option>
      <option value="Virginia">VA</option>
      <option value="Washington">WA</option>
      <option value="West Virginia">WV</option>
      <option value="Wisconsin">WI</option>
      <option value="Wyoming">WY</option>
    </select><br />
    ZIP Code: <input type="text" name="zip"><br />
    <input type="submit" value="Submit">
    </form>

  8. #8
    Join Date
    Oct 2013
    Posts
    490
    OK, cool!

    Part of my point above was that choosing your form tags and attributes wisely can actually eliminate any reason for validating at least some of those inputs, client-side or server-side.

    Look, if you limit the users' choices to only valid options there's no need to validate! The inputs "self-validate". That's why I suggested a <select> for the state input. When the options are: <option value="AL">Alabama</option> (and etc.) you've pre-validated that input.

    I'm gonna back-pedal a bit on the <input type="date"> as it doesn't work well in IE and Firefox -- OK, not at all . But here's an alternative:
    HTML Code:
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>date 'validation'</title>
    <script>
    function days(el,y){
    	switch (el.value){
    		case 'April':
    		case 'June':
    		case 'September':
    		case 'November':
    			document.getElementById('31').style.display='none';	// 30 day months
    		break;
    		case 'February':
    			if ((y.value == '2016') || (y.value == '2020')){	// leap years
    				document.getElementById('31').style.display='none';
    				document.getElementById('30').style.display='none';
    			}
    			else{							// non leap years
    				document.getElementById('31').style.display='none';
    				document.getElementById('30').style.display='none';
    				document.getElementById('29').style.display='none';
    			}
    		break;
    		default:							// all other months
    			document.getElementById('31').style.display='inline';
    			document.getElementById('30').style.display='inline';
    			document.getElementById('29').style.display='inline';
    		break;
    	}
    }
    </script>
    </head>
    <body>
    
    <form action="#">
    <label for="year">Year:</label> 
    <select id="year" name="year">
    	<option value="2014">2014</option>
    	<option value="2015">2015</option>
    	<option value="2016">2016</option>
    	<option value="2017">2017</option>
    	<option value="2018">2018</option>
    	<option value="2019">2019</option>
    	<option value="2020">2020</option>
    </select><br>
    <label for="month">Month:</label> 
    <select id="month" name="month" onchange="days(this,year)">
    	<option value="January">January</option>
    	<option value="February">February</option>
    	<option value="March">March</option>
    	<option value="April">April</option>
    	<option value="May">May</option>
    	<option value="June">June</option>
    	<option value="July">July</option>
    	<option value="August">August</option>
    	<option value="September">September</option>
    	<option value="October">October</option>
    	<option value="November">November</option>
    	<option value="December">December</option>
    </select><br>
    <label for="day">Day:</label> 
    <select id="day" name="day">
    	<option value="01">1</option>
    	<option value="02">2</option>
    	<option value="03">3</option>
    	<option value="04">4</option>
    	<option value="05">5</option>
    	<option value="06">6</option>
    	<option value="07">7</option>
    	<option value="08">8</option>
    	<option value="09">9</option>
    	<option value="10">10</option>
    	<option value="11">11</option>
    	<option value="12">12</option>
    	<option value="13">13</option>
    	<option value="14">14</option>
    	<option value="15">15</option>
    	<option value="16">16</option>
    	<option value="17">17</option>
    	<option value="18">18</option>
    	<option value="19">19</option>
    	<option value="20">20</option>
    	<option value="21">21</option>
    	<option value="22">22</option>
    	<option value="23">23</option>
    	<option value="24">24</option>
    	<option value="25">25</option>
    	<option value="26">26</option>
    	<option value="27">27</option>
    	<option value="28">28</option>
    	<option value="29" id="29">29</option>
    	<option value="30" id="30">30</option>
    	<option value="31" id="31">31</option>
    </select>
    </form>
    </body>
    </html>
    Notice that there's no "validation" even in the script. The user is presented with valid choices and only valid choices. All the script does is figure a "valid" number of days for the month chosen. Even if a user has JS turned off the worst that happens is that you get a February 31 sent to you. Probably not the end of the world.

    It could be written a bit better, but I kinda threw it together . FYI this doesn't work in IE8-. But in any modern browser it should work as intended.

    Also, what's a "valid" date? Is it 7/27/14? 07/27/2014? July 27, 2014? 27 July 14? 07/08/14 can be July 8, 2014 or August 7, 2014 depending on the part of the world you live in. See the problem? The point behind my code above is that the user is "forced" into choosing valid months, days, and years. Then you can combine them any way you want on the server.


    Gack, I just saw your code as I was writing this. Need some time on that. First impression: I hate JS alerts except for debugging purposes.

  9. #9
    Join Date
    Jul 2014
    Posts
    15
    @ Kevin2

    Thanks for the feed back I really appreciate it. Great ideas on the date field and in general I agree with your way of going about this. The "valid date" I honestly have no idea, that's how it was asked so I'm not going to worry too much over that.

    Regarding the alerts, unfortunately I've heard from quite a few people that the way we were being taught by this guy wasn't the best...

    I'm stuck currently on the ZIP code portion, any suggestions what I'm doing wrong there? When I have it there, all validations (alerts) break, but when I remove it, they all work. So I narrowed it down to that portion...
    Last edited by jedaisoul; 07-28-2014 at 03:12 AM. Reason: lengthy quote deleted

  10. #10
    Join Date
    May 2014
    Posts
    936
    1) It would help if you used a complete form. Where are you LABEL, FIELDSET, FOR attributes, and ID's?

    2) Might also help to NOT use the decade out of date nyetscape 4 style array indexing of fields.

    3) If you are going to perform the same operation over and over, put it in a bloody function.

    4) assuming the element exists, it should NEVER return null. There's no reason to check that.

    5) might be more useful to mark the invalid fields with a class and add the error message to the markup instead of using an alert.

    6) Just let people type in the bloody state. Selects of anything more than 12 OPTION is annoying crap.

    7) don't waste time server-side sending the full state name...

    8) It's better for the scripting to hook the form instead of the other way around -- it's why I say the various onevent attributes in HTML like onsubmit should be removed from the specification.

    So first, let's drag your markup kicking and screaming into being a properly built form:

    Code:
    <form action="#" id="registerForm" method="post">
    	<fieldset>
    
    		<label for="register_firstName">First name:</label>
    		<input
    			type="text"
    			class="v_required"
    			name="firstName"
    			id="register_firstName"
    		 /><br />
    
    		<label for="register_lastName">Last Name:</label>
    		<input
    			type="text"
    			class="v_required"
    			name="lastName"
    			id="register_lastName"
    		/><br />
    		
    		<label for="register_address1">Address Line 1:</label>
    		<input
    			type="text"
    			class="v_required"
    			name="address1"
    			id="register_address1"
    		/><br />
    		
    		<label for="register_address2">Address Line 2:</label>
    		<input
    			type="text"
    			name="address2"
    			id="register_address2"
    		/><br />
    		
    		<label for="register_city">City:</label>
    		<input
    			type="text"
    			class="v_required"
    			name="city"
    			id="register_city"
    		/><br />
    		
    		<label for="register_state">State:</label>
    		<input
    			type="text"
    			class="v_required v_state"
    			name="state"
    			id="register_state"
    			maxlength="2"
    		/><br />
    		
    		<label for="register_zip">Zip Code:</label>
    		<input
    			type="text"
    			class="v_required v_USzip"
    			name="zip"
    			id="register_zip"
    			maxlength="10"
    		/><br />
    		
    	</fieldset>
    	
    	<div class="submitsAndHiddens">
    		<input type="submit" value="Submit" />
    	</div>
    	
    </form>
    I always put submits and hiddens in a DIV instead of a fieldset since they're not user input elements -- and as such aren't true "fields" -- a VALID form has a block level container or two between the FORM and the INPUT, since INPUT are NOT valid children of FORM.

    http://htmlhelp.com/reference/html40/forms/form.html

    See 'contents' for 'strict'. You're not supposed to be putting INPUT inside FORM without another wrapper in there -- like FIELDSET. (hell, it's why FIELDSET EXISTS!!!) -- same goes for not using label tags. It's just inaccessible crap without them.

    Now, as to the scripting, gimme a while and I'll belt out something far, FAR more effective. Those classes I added with the v_ are there for the script to just go through the elements and add the appropriate classes, warnings and validations.
    Java is to JavaScript as Ham is to Hamburger.

  11. #11
    Join Date
    Jul 2014
    Posts
    15
    @ deathshadow

    Thanks Deathshadow for all of the input - as noted earlier unfortunately I'm being taught poor habits so I'm trying to adjust them by learning things online (unfortunately though his timeline makes that a bit annoying).

    I do appreciate all of the input though, that all makes great sense. I'm going to check out your modifications and the link now.
    Last edited by jedaisoul; 07-28-2014 at 03:13 AM. Reason: lengthy quote deleted

  12. #12
    Join Date
    May 2014
    Posts
    936
    Oh, and @kevin2, you do know selects like that can REALLY piss off users, right? Whenever I encounter that on things like dates I end up screaming at the screen "Oh for *** sake, just let me type it in!"
    Java is to JavaScript as Ham is to Hamburger.

  13. #13
    Join Date
    Oct 2013
    Posts
    490
    My point, as I stated, was to limit user choices for "validation" purposes. If you want to write the code to validate any little bit of text entered into a <input type="text"> field and then "piss them off" with error messages by all means do so.....
    Last edited by Kevin2; 07-27-2014 at 04:49 PM.

  14. #14
    Join Date
    May 2014
    Posts
    936
    Usually if you 'piss them off' with errors, there's something wrong with your labels.

    Though dates in general are a royal pain in the ass.

    In any case, here's my example:

    http://www.cutcodedown.com/for_other.../template.html

    As with all my examples the directory:
    http://www.cutcodedown.com/for_others/Minnesota31/form/

    Is unlocked for easy access to the bits and pieces. Couple minor changes to the markup, but for the most part it's what I was talking about. The use of classes as triggers means the validation can be automated so you don't have to hard-code every single field, and instead can just loop through them. Uses an anonymous function so no risk of namespace collisions, and auto-attaches itself to the form and uses DOM manipulation for the error and element walking.

    It's also designed to hook multiple forms on a page so you can check each individually -- just add the 'validate' class to any form you want validation on, and load this script right before </body>.
    Java is to JavaScript as Ham is to Hamburger.

  15. #15
    Join Date
    May 2014
    Posts
    936
    Oh, and just because you use a select, doesn't mean you shouldn't still check it server side -- sadly it's easy enough to fake postData or even edit the form live with developer tools to turn that select into an input.

    ALL user input is suspect -- it's like how you should NEVER even trust the fieldnames returned by the form, and instead should dictate them from the PHP. I've seen this mistake a few times in forum softwares, and it's a laugh:

    <input type="text" name="user[theme]" />
    <input type="text" name="user[avatar]" />
    ... etc, etc...

    Where they then did:

    foreach ($_POST[user] as $fieldName => $fieldData) {

    Then ran a insert query on each thus:

    INSERT INTO userData
    `' . $fieldName . '` = `' . $fieldData . '`
    WHERE ID = `' . userId . '`

    Laughably vulnerable to attack. (though mysqli and PDO can make it a little better, fieldnames should be hard coded). Hit SMF about a decade ago, several WP plugins did it on 2.x, vBull did it on one of their more recent updates... and I think laughably myBB still does it :/

    So saying "can actually eliminate any reason for validating at least some of those inputs, client-side or server-side." -- uhm... no. At least not server-side. NEVER trust ANYTHING server-side.
    Java is to JavaScript as Ham is to Hamburger.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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



Recent Articles