jQuery: The Write Less, Do More JavaScript Library

Changeset 1370

Show
Ignore:
Timestamp:
02/18/07 18:46:36 (1 year ago)
Author:
joern
Message:

validation alpha 2

Location:
branches/joern-dev/fuzz/validation
Files:
1 added
4 modified

Legend:

Unmodified
Added
Removed
  • branches/joern-dev/fuzz/validation/formPluginIntegration.html

    r1288 r1370  
    2121        <p> 
    2222            <label for="user">Username</label> 
    23             <input id="user" name="user" title="Please enter your username (at least 3 characters)" class="{minLength:3}" /> 
     23            <input id="user" name="user" title="Please enter your username (at least 3 characters)" class="{required:true,minLength:3}" /> 
    2424        </p> 
    2525        <p> 
    2626            <label for="pass">Password</label> 
    27             <input type="password" name="password" id="password" class="{minLength:5}" /> 
     27            <input type="password" name="password" id="password" class="{required:true,minLength:5}" /> 
    2828        </p> 
    2929        <p> 
     
    4848        }); 
    4949         
    50         // validate the form when it is submitted 
    51         var options = { 
    52             debug: true, 
     50        $.validator.defaults.debug = true; 
     51         
     52        $("#form").validate({ 
    5353            submitHandler: function(form) { 
    5454                $(form).ajaxSubmit({ 
     
    6161                    } 
    6262                }); 
    63             } 
    64         }; 
    65         var v = $("#form").validate(options); 
     63            }, 
     64            event: "keyup" 
     65        }); 
    6666    }); 
    6767</script> 
  • branches/joern-dev/fuzz/validation/js/validate.js

    r1363 r1370  
    1010 
    1111/** 
    12  * Validates either a single form on submit or a list of elements immediately. 
     12 * Validates either a single form on submit or a list of elements on a user-defined event. 
    1313 * 
    1414 * The normal behaviour is to validate a form when a submit button is clicked or 
    1515 * the user presses enter when an input of that form is focused. 
    1616 * 
    17  * It is also possible to validate elements immediately on blur or any other event. 
     17 * It is also possible to validate each individual element of that form, eg. on blur or keyup. 
    1818 * 
    1919 * Following are a few aspects that you should know about when using this plugin. 
     
    2222 * Markup recommendations: A good form has labels associated with each input 
    2323 * element: The for attribute of the label has the same value as the id of the input. 
    24  * 
    25  * Validation rules: You can specify validation rules via metadata or via plugin 
    26  * settings (option rules). Its more a matter of taste which way you choose. 
    27  * Using metadata is good for fast prototyping. 
    28  * 
    29  * Validation methods: Included are a set of common validation methods, like required. 
     24 * If IDs aren't provided, they are generated, combining the ID of the containing 
     25 * form (if any) with the name of the element, with the exception of radio and checkbox 
     26 * inputs. 
     27 * 
     28 * Validation methods: A valiation method decides whether an element is valid. 
     29 * Included are a set of common validation methods, like required. 
    3030 * Except required itself and equalTo, all validation methods declare an element valid 
    3131 * when it has no value at all. That way you can specify an element input to 
    3232 * contain a valid email adress, or nothing at all. All available methods are documented 
    3333 * below, as well as $.validator.addMethod, which you can use to add your own methods. 
     34 * 
     35 * Validation rules: A validation rule applies one or more validation methods to an 
     36 * input element. You can specify validation rules via metadata or via plugin 
     37 * settings (option rules). It is more a matter of taste which way you choose. 
     38 * Using metadata is good for fast prototyping. Plugin settings are good for perfect 
     39 * clean markup. Valid markup results from both approaches. 
    3440 *  
    35  * Error messages: There are three ways to provide error messages. Via the title attribute 
    36  * of the input element to validate, via error labels and via plugin settings 
    37  * (option messages). All included validation rules provide a default error message 
    38  * which you can use for prototyping. 
     41 * Error messages: An error message displays a hint for the user about invalid 
     42 * elements, and what is wrong. There are three ways to provide error messages. 
     43 * Via the title attribute of the input element to validate, via error labels and 
     44 * via plugin settings (option messages). All included validation rules provide a 
     45 * default error message which you can use for prototyping, because it is used when 
     46 * no specific message is provided. 
    3947 * 
    4048 * Error message display: Error messages are handled via label elements with an 
     
    4351 * after the invalid element. It is also possible to put them into an error container 
    4452 * (option errorContainer), even a container containing a general warning followed by 
    45  * the list of errors is possible (option errorContainer together with errorLabelContainer). 
     53 * a list of errors is possible (option errorContainer together with errorLabelContainer). 
    4654 * 
    4755 * Focusing of invalid elements: By default, the first invalid element in a form is focused 
     
    5462 * Form submit: By default, the form submission is prevented when the form is invalid, 
    5563 * and submitted as normal when it is valid. You can also handle the submission 
    56  * (option submitHandler) manually. 
     64 * manually (option submitHandler). 
     65 * 
     66 * Validation event: By default, forms are validated on submit, triggered by the user clicking 
     67 * the submit button or pressing enter when a form input is focused. Instead, each element can 
     68 * be validated on a certain event like blur or keyup (option event). 
    5769 * 
    5870 * Developing and debugging a form: While developing and debugging the form, you should set 
     
    6274 * your rules all accept empty elements as valid (like email or url methods). 
    6375 * 
    64  * Validation multiple forms on one page: The plugin can handle only one form per call. In case 
     76 * Validating multiple forms on one page: The plugin can handle only one form per call. In case 
    6577 * you have multiple forms on a single page which you want to validate, you can avoid having 
    66  * to duplicate the plugin settings by modifying the defaults via $.validator.defaults. 
    67  * 
    68  * Validator object: The validation plugin returns the instance of the validator object it uses. 
     78 * to duplicate the plugin settings by modifying the defaults via $.validator.defaults. Use 
     79 * $.extend($.validator.defaults, {...}) to override multiple settings at once. 
     80 * 
     81 * Validator object: The validation plugin method returns the instance of the validator object it uses. 
    6982 * That gives you full control over every aspect of the validation. Let me know if you come up 
    7083 * with something that I didn't have in mind. Thats why the plugin has nearly no private methods. 
     
    7689 * @desc Validates a form on submit. Rules are read from metadata. 
    7790 * 
    78  * @example $("input").blur(function() { 
    79  *   $(this).validate({ 
    80  *     focusInvalid: false 
    81  *   }); 
     91 * @example $("input").validate({ 
     92 *      focusInvalid: false, 
     93 *      event: blur 
    8294 * }); 
    8395 * @desc Validates all input elements on blur event (when the element looses focus). 
     
    197209 *      blur or keypress, each element is validated on that event. Default: submit, 
    198210 *      validates the entire form on submit 
     211 * @option Boolean onsubmit Validate the form on submit. Set to false to use only other 
     212 *      events for validation (option event). Default: true 
    199213 * @option String metaWrapper In case you use metadata for other plugins, too, you 
    200214 *      want to wrap your validation rules 
     
    210224$.fn.validate = function(options) { 
    211225    var validator = new $.validator(options, this); 
    212     if( !validator.settings.event ) { 
     226    if( validator.settings.onsubmit ) { 
    213227        // validate the form on submit 
    214228        this.submit(function(event) { 
     
    219233            return validator.validateForm(); 
    220234        }); 
    221     } else { 
     235    } 
     236    if( validator.settings.event ) { 
    222237        // validate all elements on some other event like blur or keypress 
    223238        validator.elements[validator.settings.event](function() { 
     
    243258    this.currentForm = form[0]; 
    244259    // find the element to look for error labels 
    245     this.errorContext = settings.errorLabelContainer.length && settings.errorLabelContainer 
     260    this.errorContainer = settings.errorLabelContainer.length && settings.errorLabelContainer 
    246261        || settings.errorContainer.length && settings.errorContainer 
    247         || this.currentForm; 
     262        || $([]) 
     263    this.errorContext = this.errorContainer.length && this.errorContainer || form; 
    248264     
    249265    // listen for focus events to save reference to last focused element 
     
    267283    focusInvalid: true, 
    268284    errorContainer: $([]), 
    269     errorLabelContainer: $([]) 
     285    errorLabelContainer: $([]), 
     286    onsubmit: true 
    270287}; 
    271288 
     
    323340                    } 
    324341                    var list = this.errorList[id] || (this.errorList[id] = []); 
    325                     list[list.length] = method.message && this.formatMessage(method.message, rule.parameters); 
     342                    list[list.length] = method.message && this.formatMessage(method.message, rule, id); 
    326343                } 
    327344            } catch(e) { 
     
    345362     * @param Array<Object>|Object param 
    346363     */ 
    347     formatMessage: function(message, param) { 
    348         var first = param.constructor == Array ? param[0] : param; 
     364    formatMessage: function(message, rule, id) { 
     365        var m = this.settings.messages, 
     366            param = rule.parameters, 
     367            first = param.constructor == Array ? param[0] : param; 
     368        if(m && m[id]) { 
     369            if(m[id].constructor == String) 
     370                message = m[id]; 
     371            else 
     372                message = m[id][rule.name]; 
     373        } 
    349374        return message.replace("{0}", first || "").replace("{1}", param[1] || ""); 
    350375    }, 
     
    384409                return false; 
    385410            } 
    386             if(this.settings.debug && window.console) 
    387                 console.log("form is valid (or rules have errors)") 
    388411            return true; 
    389412        } 
     
    431454     */ 
    432455    showError: function(elementID, message) { 
    433         var element = $("#" + elementID).addClass(this.settings.errorClass); 
    434      
    435         // find message for this label 
    436         var m = this.settings.messages; 
    437         var message = (m && m[elementID]) || element.attr('title') || message || "<strong>Warning: No message defined for " + elementID + "</strong>"; 
    438          
    439         var errorLabel = $("label." + this.settings.errorClass, this.errorContext) 
    440             .filter("[@for=" + elementID + "]"); 
    441         var w = this.settings.errorWrapper; 
     456        var element = $("#" + elementID).addClass(this.settings.errorClass), 
     457            // find message for this label 
     458            message = element.attr('title') || message || "<strong>Warning: No message defined for " + elementID + "</strong>", 
     459            errorLabel = $("label." + this.settings.errorClass, this.errorContext).filter("[@for=" + elementID + "]"), 
     460            wrapper = this.settings.errorWrapper; 
    442461        if( errorLabel.length ) { 
    443462            // check if we have a generated label, replace the message then 
     
    446465            } 
    447466            errorLabel.show(); 
    448             if( w ) { 
    449                 errorLabel.parents(w).show(); 
     467            if(wrapper) { 
     468                errorLabel.parents(wrapper).show(); 
    450469            } 
    451470        } else { 
     
    454473            // TODO can't change message 
    455474            var errorLabel = $("<label>").attr({"for": elementID, generated: true}).addClass("error").html(message); 
    456             if(w) { 
    457                 errorLabel = errorLabel.show().wrap("<" + w + "></" + w + ">").parent(); 
     475            if(wrapper) { 
     476                errorLabel = errorLabel.show().wrap("<" + wrapper + "></" + wrapper + ">").parent(); 
    458477            } 
    459             if(!this.errorContext.append(errorLabel).length)  
     478            if(!this.errorContainer.append(errorLabel).length)  
    460479                errorLabel.insertAfter(element); 
    461480            errorLabel.show(); 
     
    473492        } else { 
    474493            data = $(element).data(); 
    475             var meta = this.settings.metaWrapper; 
    476             if(meta) 
    477                 data = data[meta]; 
     494            var metaWrapper = this.settings.metaWrapper; 
     495            if(metaWrapper) 
     496                data = data[metaWrapper]; 
    478497        } 
    479498        var rules = []; 
    480499        if(!data) 
    481500            return rules; 
    482         $.each(data, function(key) { 
     501        $.each(data, function(key, value) { 
    483502            var rule = rules[rules.length] = {}; 
    484503            rule.name = key; 
    485             rule.parameters = this; 
     504            rule.parameters = value; 
    486505        }); 
    487506        return rules; 
     
    492511        // generate id when none is found 
    493512        if(!id) { 
    494             var formId = element.form.id; 
    495             var id = element.id = (formId ? formId.replace(/[^a-zA-Z0-9\-_]/g, "") : "") + element.name.replace(/[^a-zA-Z0-9\-_]/g, ""); 
     513            var formId = element.form.id, 
     514                idcleanup = /[^a-zA-Z0-9\-_]/g; 
     515            id = element.id = (formId ? formId.replace(idcleanup, "") : "") + element.name.replace(idcleanup, ""); 
    496516        } 
    497517        return id; 
     
    595615            } 
    596616        default: 
    597             return value.length > 0; 
     617            return $.trim(value).length > 0; 
    598618        } 
    599619    }, 
  • branches/joern-dev/fuzz/validation/validateCustomTest.html

    r1362 r1370  
    1515<body> 
    1616 
    17 <div id="texttests"> 
     17<form action="foo.html" id="texttests"> 
    1818 
    1919    <h2>Some more tests with text and textarea and validating on blur</h2> 
     
    2525        textarea 
    2626        <textarea id="textarea" cols="25" rows="5" 
    27             title="Please enter a date with at least 3 and max 15 characters! (length and date)" 
     27            title="Please enter a number with at least 3 and max 15 characters!" 
    2828            test="required:true, minLength:3, maxLength:15, number:true"></textarea> 
    2929        <br/> 
     
    5858        <label for="family" class="error">Please select your family status.</label> 
    5959    </div> 
    60  
    61 </div> 
     60    <input type="submit" /> 
     61</form> 
    6262 
    6363<script type="text/javascript"> 
     
    8181    $(document).ready(function() { 
    8282        $.validator.defaults.debug = true; 
    83         var options = { 
     83         
     84        $("#texttests").validate({ 
    8485            // important: combining focus with validation on blur can crash browsers 
    8586            focusInvalid: false, 
    86             event: "blur" 
    87         }; 
    88          
    89         $("#texttests").validate(options); 
     87            event: "blur", 
     88            onsbumit: false 
     89        }); 
    9090         
    9191    }); 
  • branches/joern-dev/fuzz/validation/validateTest.html

    r1288 r1370  
    7777    <li><a href="validateRadioTest.html">A very simple test to validate radio buttons</a></li> 
    7878    <li><a href="validateCheckboxTest.html">A very simple test to validate checkbox buttons</a></li> 
     79    <li><a href="validatKeypressTest.html">Validation on keypress and submit</a></li> 
    7980    <li><a href="formPluginIntegration.html">Integration with Form Plugin (AJAX submit)</a></li> 
    8081</ul>