UMass Lowell Dept. of Computer Science

91.461 GUI Programming I

Fall 2015 Semester, Section 201

Prof. Jesse M. Heines

Notes for Class No. 18

Using the jQuery Validation Plugin

Tuesday, November 3, 2015

A video of this class is (or will be) posted at:   http://echo360.uml.edu/heines201516/guiprogramming1.html


Handouts and Materials


Openings / Announcements / Reminders

Assignment No. 6 Graders’ Comments

Mike

Greg


Class Notes


Using the jQuery Validation plugin


History

The plugin is written and maintained by Jörn Zaefferer

It was started back in the early days of jQuery in 2006, and [has been] updated and improved since then.


Local Installation

  1. download the plugin to a directory that is accessible to your website
  2. link to the required files from your web page
<!-- the jQuery Validation Plugin is from http://bassistance.de/jquery-plugins/jquery-plugin-validation -->
<script src="/~heines/jQuery/plugins/jquery-validation-1.11.1/jquery.validate.min.js"></script>
<script src="/~heines/jQuery/plugins/jquery-validation-1.11.1/additional-methods.min.js"></script>

Multiplication Table Generator, Version 5, which adds validation using the jQuery Validation plugin


Technique #1:  Adding validation rules as classes

Table 9-2.  The Validation plugin includes methods that cover the most common validation needs.  Source: JS&jQ:TMM, p. 282.
Rule Explanation
required The field won’t be submitted unless this field is filled out, checked, or selected.
date Information must be in the format MM/DD/YYYY.  For example, 10/30/2009 is considered valid, but 10-30-2009 is not.
url Must be a full, valid web address like http://www.chia-vet.com.  Partial URLs such as www.chia-vet.com or chia-vet.com are considered invalid.
email Must be formatted like an email address: bob@chia-vet.com.  This class doesn’t actually check to make sure the email address is real, so someone could still enter nobody@noplace.com and the field would pass validation.
number Must be a number like 32 or 102.50 or even –145.5555.  However, the input can’t include any symbols, so $45.00 and 100,000 are invalid.
digits Can only include positive integers. So 1, 20, 12333 are valid, but 10.33 and –12 are not valid.
creditcard Must be a validly formatted credit card number.


Technique #2:  Using advanced rules in JSON format

This code starts at line 760 in the PDF code listing

(1)  Set up a handler for the validate function

$( '#idOfForm' ).validate( {
  // options go here
} ) ; // end validate();

(2)  Specify options in JSON format

rules: {
  "fieldname"  : "validationType" ,
  "fieldname2" : "validationType" ,
  // etc.
}

Example  (JS&jQ:TMM p. 286)

 1  $( '#signup' ).validate( {
 2    rules: {
 3      name: 'required',
 4      email: {
 5        required: true,
 6        email: true 
 7      }
 8    }
 9  } ) ;  // end validate()
Advanced Validation plugin rules.  Source: JS&jQ:TMM, p. 287-288.
Rule Explanation
minlength The field must contain at least the specified number of characters.  For example, the rule to make sure that at least six characters are entered into a field is this: minlength: 6
maxlength The field must contain no more than the specified number of characters.  For example, the rule to ensure that no more than 100 characters are entered into the field looks like this: maxlength:100
rangelength A combination of both minlength and maxlength.  Specifies both the minimum and maximum number of characters allowed in a field.  For example, the rule to make sure a field contains at least six characters but no more than 100 is as follows: rangelength:[6,100]
min Requires that the field contain a number that’s equal to or greater than the specified number.  For example, the following rule requires that the field both contains a number and that the number is greater than or equal to 10: min:10.  In this example, if the visitor enters 8, the field won’t validate because 8 is less than 10.  Likewise, if your visitor types a word — eight, for example — the field won’t validate and she’ll get an error message.
max Like min, but specifies the largest number the field can contain.  To make sure a field contains a number less than 1,000, for example, use the following: max:1000
range Combines min and max to specify both the smallest and largest numbers that the field must contain.  For example, to make sure a field contains at least 10 but no more than 1,000, use this: range:[10,1000]
equalTo Requires that a field’s contents match another field.  For example, on a sign-up form, it’s common to ask a visitor to enter a password and then verify that password by typing it a second time.  This way, the visitor can make sure he or she didn’t mistype the password the first time.  To use this method, you must specify a string containing a valid jQuery selector.  For example, say the first password field has an ID of password applied to it.  If you want to make sure the “verify password” field matches the first password field, you use this code: equalTo: "#password"

(3)  If desired, specify custom error messages

messages: {
  fieldname: {
    methodType: 'Error message'
  } ,
  fieldname2: {
    methodType: 'Error message'
  }
}

Example  (JS&jQ:TMM p. 290)

(4)  If desired, specify the error message position (see Step 4 in the tutorial in JS&jQ:TMM p. 298)

(5)  If desired, specify what should be done when a field passes validation

(6)  If desired, style your error messages

Summary of Validation plugin configuration sections


Interesting post by student Chris Burbine  (GUI Programming I, Fall 2013, continued)

Issue with my addMethod lessThanEqualhttps://piazza.com/class/hi2cfz0f9096iw?cid=61

Having some issues with my code. Wanted to create a method for my validation that check to see if one number was less than or equal to another, but I have run into some issues.  NetBeans keep spitting back the error "Uncaught TypeError: Cannot call method 'toLowerCase' of undefined".  It then points me to the jQuery Validation file I have linked to the program. The remaining lines of errors look like this:

Uncaught TypeError: Cannot call method 'toLowerCase' of undefined (10:51:02:640 | error, javascript) 
      at x.fn.extend.val (http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js:5:6227) 
      at (public_html/index.html:15:91) 
      at t.extend.check (public_html/jquery.validate.min.js:2:8996) 
      at t.extend.element (public_html/jquery.validate.min.js:2:6450) 
      at t.extend.defaults.onfocusout (public_html/jquery.validate.min.js:2:3233) 
      at e (public_html/jquery.validate.min.js:2:4844) 
      at (public_html/jquery.validate.min.js:2:20926) 
      at x.event.dispatch (http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js:5:14129) 
      at v.handle (http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js:5:10866) 
      at x.event.trigger (http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js:5:13255)

I’ve written up a small example code to test just this method (see http://www.cs.uml.edu/~cburbine/lessthantest.html).  The console spits out the same error. Any help would be appreciated.  Thank you.

My response

The problem is that you're not using the parameters to the function passed to your addMethod correctly.  The error is being cause by your return statement:

return this.optional(element) || parseInt(value) <= parseInt($(param).val());

There are actually two problems.

First, your rule states:

lessThanEqual : true 

You should not be passing a Boolean here, you should be passing a number, such as:

lessThanEqual : 10

Second, your return statement (above) tries to get the value (.val()) of something is not an HTML element ($(param)).  param is not an element, so $(param) is not an element, so $(param).val() is meaningless.  This is what is causing the jQuery validate plugin to crash.  

To correct this second problem, use:

return this.optional(element) || parseInt(value) <= param ;

Now, the interesting part here is how I figured all this out.  I had not used the addMethod feature before, so I had to look it up.  This is the trick to using APIs: knowing where to look things up and understanding how to interpret what you find there.  To analyze your code I added five console.log statements:

console.log( "value = " + value + " (" + typeof( value ) + ")" ) ;
console.log( "element = " + element + " (" + typeof( element ) + ")" ) ;
console.log( "$(element).val() = " + $(element).val() ) ;
console.log( "param = " + param + " (" + typeof( param ) + ")" ) ;
console.log( "this.optional(element) = " + this.optional(element) ) ;

which, when I typed a 1, produced the following output:

value = 1 (string)
element = [object HTMLInputElement] (object)
$(element).val() = 1
param = 10 (number)
this.optional(element) = false

Once I had these insights on what was passed, fixing the code was rather easy.

Runnable Code

Design Questions



This is document http://jesseheines.com:8080/~heines/91.461/91.461-2015-16f/461-lecs/lecture18.jsp.  It was last modified on Friday, August 26, 2022 at 4:09 PM.
Copyright © 2022 by Jesse M. Heines.  All rights reserved.  May be freely copied or excerpted for educational purposes with credit to the author.