From fe07dc3f634d9c8816871d822120574efce30928 Mon Sep 17 00:00:00 2001 From: Rick Harrison Date: Sun, 16 Oct 2011 22:43:28 -0700 Subject: [PATCH 01/40] Finalized the 1.0 release. --- .gitignore | 1 + LICENSE | 19 +++ README.md | 46 +++++++ validate.js | 338 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 404 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 README.md create mode 100644 validate.js diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e43b0f9 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +.DS_Store diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..c986edd --- /dev/null +++ b/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2011 by Rick Harrison, http://rickharrison.me + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..0edbf58 --- /dev/null +++ b/README.md @@ -0,0 +1,46 @@ +# validate.js + +validate.js is a lightweight JavaScript form validation library inspired by CodeIgniter. + +## Features + +- Validate form fields from over a dozen rules +- No dependencies +- Customizable Messages +- Supply your own validation callbacks for custom rules +- Chainable customization methods for ease of declaration +- Works in all major browsers, (even IE6!) +- Modeled off the CodeIgniter form validation API + +## How to use + + var validater = new FormValidater('example_form', [{ + name: 'req', + display: 'required', + rules: 'required' + }, { + name: 'alphanumeric', + rules: 'alpha_numeric' + }, { + name: 'password', + rules: 'required' + }, { + name: 'password_confirm', + display: 'password confirmation', + rules: 'required|matches[password]' + }, { + name: 'email', + rules: 'valid_email' + }, { + name: 'minlength', + display: 'min length', + rules: 'min_length[8]' + }], function(errors) { + if (errors.length > 0) { + // Show the errors + } + }); + +## Documentation + +You can view everything at http://rickharrison.github.com/validate.js diff --git a/validate.js b/validate.js new file mode 100644 index 0000000..b710979 --- /dev/null +++ b/validate.js @@ -0,0 +1,338 @@ +/* + * validate.js 1.0.0 + * Copyright (c) 2011 Rick Harrison, http://rickharrison.me + * validate.js is open sourced under the MIT license. + * Portions of validate.js are inspired by CodeIgniter. + * http://rickharrison.github.com/validate.js + */ + +(function(window, document, undefined) { + /* + * If you would like an application-wide config, change these defaults. + * Otherwise, use the setMessage() function to configure form specific messages. + */ + + var defaults = { + messages: { + required: 'The %s field is required.', + matches: 'The %s field does not match the %s field.', + valid_email: 'The %s field must contain a valid email address.', + min_length: 'The %s field must be at least %s characters in length.', + max_length: 'The %s field must not exceed %s characters in length.', + exact_length: 'The %s field must be exactly %s characters in length.', + greater_than: 'The %s field must contain a number greater than %s.', + less_than: 'The %s field must contain a number less than %s.', + alpha: 'The %s field must only contain alphabetical characters.', + alpha_numeric: 'The %s field must only contain alpha-numeric characters.', + alpha_dash: 'The %s field must only contain alpha-numeric characters, underscores, and dashes.', + numeric: 'The %s field must contain only numbers.', + integer: 'The %s field must contain an integer.' + }, + callback: function(errors) { + + } + }; + + /* + * Define the regular expressions that will be used + */ + + var ruleRegex = /^(.+)\[(.+)\]$/, + numericRegex = /^[0-9]+$/, + integerRegex = /^\-?[0-9]+$/, + decimalRegex = /^\-?[0-9]*\.?[0-9]+$/, + emailRegex = /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,6}$/i, + alphaRegex = /^[a-z]+$/i, + alphaNumericRegex = /^[a-z0-9]+$/i, + alphaDashRegex = /^[a-z0-9_-]+$/i; + + /* + * The exposed public object to validate a form: + * + * @param formName - String - The name attribute of the form (i.e.
) + * @param fields - Array - [{ + * name: The name of the element (i.e. ) + * display: 'Field Name' + * rules: required|matches[password_confirm] + * }] + * @param callback - Function - The callback after validation has been performed. One argument of an array of possible errors + */ + + var FormValidater = function(formName, fields, callback) { + this.callback = callback || defaults.callback; + this.errors = []; + this.fields = {}; + this.form = document.forms[formName] || {}; + this.messages = {}; + this.handlers = {}; + + for (var i = 0, fieldLength = fields.length; i < fieldLength; i++) { + var field = fields[i]; + + // If passed in incorrectly, we need to skip the field. + if (!field.name || !field.rules) { + continue; + } + + /* + * Build the master fields array that has all the information needed to validate + */ + + this.fields[field.name] = { + name: field.name, + display: field.display || field.name, + rules: field.rules, + type: null, + value: null, + checked: null + } + } + + /* + * Attach an event callback for the form submission + */ + + this.form.onsubmit = (function(that) { + return function(event) { + try { + return that._validateForm(event); + } catch(e) {} + } + })(this); + }; + + FormValidater.prototype.setMessage = function(rule, message) { + this.messages[rule] = message; + + // return this for chaining + return this; + }; + + /* + * @public + * Registers a callback for a custom rule (i.e. callback_username_check) + */ + + FormValidater.prototype.registerCallback = function(name, handler) { + if (name && typeof name === 'string' && handler && typeof handler === 'function') { + this.handlers[name] = handler; + } + + // return this for chaining + return this; + }; + + /* + * @private + * Runs the validation when the form is submitted. + */ + + FormValidater.prototype._validateForm = function(event) { + this.errors = []; + + for (var key in this.fields) { + if (this.fields.hasOwnProperty(key)) { + var field = this.fields[key] || {}, + element = this.form[field.name]; + + if (element && element !== undefined) { + field.type = element.type; + field.value = element.value; + field.checked = element.checked; + } + + /* + * Run through the rules for each field. + */ + + this._validateField(field); + } + } + + if (typeof this.callback === 'function') { + this.callback(this.errors, event); + } + + if (this.errors.length > 0) { + if (event && event.preventDefault) { + event.preventDefault(); + } else { + // IE6 doesn't pass in an event parameter so return false + return false; + } + } + + return true; + }; + + /* + * @private + * Looks at the fields value and evaluates it against the given rules + */ + + FormValidater.prototype._validateField = function(field) { + var rules = field.rules.split('|'); + + /* + * If the value is null and not required, we don't need to run through validation + */ + + if (field.rules.indexOf('required') === -1 && (!field.value || field.value === '' || field.value === undefined)) { + return; + } + + /* + * Run through the rules and execute the validation methods as needed + */ + + for (var i = 0, ruleLength = rules.length; i < ruleLength; i++) { + var method = rules[i], + param = null, + failed = false; + + /* + * If the rule has a parameter (i.e. matches[param]) split it out + */ + + if (parts = ruleRegex.exec(method)) { + method = parts[1]; + param = parts[2]; + } + + /* + * If the hook is defined, run it to find any validation errors + */ + + if (typeof this._hooks[method] === 'function') { + if (!this._hooks[method].apply(this, [field, param])) { + failed = true; + } + } else if (method.substring(0, 9) === 'callback_') { + // Custom method. Execute the handler if it was registered + method = method.substring(9, method.length); + + if (typeof this.handlers[method] === 'function') { + if (this.handlers[method].apply(this, [field.value]) === false) { + failed = true; + } + } + } + + /* + * If the hook failed, add a message to the errors array + */ + + if (failed) { + // Make sure we have a message for this rule + var source = this.messages[method] || defaults.messages[method]; + + if (source) { + var message = source.replace('%s', field.display); + + if (param) { + message = message.replace('%s', (this.fields[param]) ? this.fields[param].display : param); + } + + this.errors.push(message); + } else { + this.errors.push('An error has occurred with the ' + field.display + ' field.'); + } + + // Break out so as to not spam with validation errors (i.e. required and valid_email) + break; + } + } + }; + + /* + * @private + * Object containing all of the validation hooks + */ + + FormValidater.prototype._hooks = { + required: function(field) { + var value = field.value; + + if (field.type === 'checkbox') { + return (field.checked === true); + } + + return (value !== null && value !== ''); + }, + + matches: function(field, matchName) { + if (el = this.form[matchName]) { + return field.value === el.value; + } + + return false; + }, + + valid_email: function(field) { + return emailRegex.test(field.value); + }, + + min_length: function(field, length) { + if (!numericRegex.test(length)) { + return false; + } + + return (field.value.length >= length); + }, + + max_length: function(field, length) { + if (!numericRegex.test(length)) { + return false; + } + + return (field.value.length <= length); + }, + + exact_length: function(field, length) { + if (!numericRegex.test(length)) { + return false; + } + + return (field.value.length == length); + }, + + greater_than: function(field, param) { + if (!decimalRegex.test(field.value)) { + return false; + } + + return (parseFloat(field.value) > parseFloat(param)); + }, + + less_than: function(field, param) { + if (!decimalRegex.test(field.value)) { + return false; + } + + return (parseFloat(field.value) < parseFloat(param)); + }, + + alpha: function(field) { + return (alphaRegex.test(field.value)); + }, + + alpha_numeric: function(field) { + return (alphaNumericRegex.test(field.value)); + }, + + alpha_dash: function(field) { + return (alphaDashRegex.test(field.value)); + }, + + numeric: function(field) { + return (decimalRegex.test(field.value)); + }, + + integer: function(field) { + return (integerRegex.test(field.value)); + } + }; + + window.FormValidater = FormValidater; + +})(window, document); From 61c95a77381f79dde07a2c1196fac78949d9bf66 Mon Sep 17 00:00:00 2001 From: Rick Harrison Date: Sun, 16 Oct 2011 23:28:57 -0700 Subject: [PATCH 02/40] Added the website assets. --- assets/background.png | Bin 0 -> 1366 bytes index.html | 364 ++++++++++++++++++++++++++++++++++++++++++ styles/main.css | 324 +++++++++++++++++++++++++++++++++++++ 3 files changed, 688 insertions(+) create mode 100644 assets/background.png create mode 100644 index.html create mode 100644 styles/main.css diff --git a/assets/background.png b/assets/background.png new file mode 100644 index 0000000000000000000000000000000000000000..4306c8cd3fa25220921900c4bcdfd9f5994b3ae3 GIT binary patch literal 1366 zcmeAS@N?(olHy`uVBq!ia0vp^e}MQI2OE(5`0T|jAjMMbV`u zzJB}nxbvT7_CEXm+qP=&*0guUy3Z@4zS^9(GySldQ_hKnU$LoO;GlEI14Wk)0!kGe zf;KH2IEC+Z{#>y4yOr&1)55cy!q0bJJ9Fpa%j&sR-#C|_|2!?de*SaIy3N~<>ic`vwofV!Z}!ib{dRAEKFht5 z`NHp?zx+MNz$odb&3RG%%er}$-&Qi7-*j2_?>~Fb1BN7o8O+)fCzjp4S6yp2|M7L3 zz3;#Nt#jY@J@4j%-KhsYe=%KN_G#b!_aC$8?YsWHa^7R{zcqHr+{?^oRJ_cO%$wWs zxh;KuM{SdT75?afS%nsv_oCgH@+I5n+~AmF1PrI@I^pEm=6k%e=iWah&0Uw2_-)Hd z@qJdiEWW;3?t8TEu=V@NI1>O48^FR7%GZ9r9l5>7;$BkLiNd6UqAczAY|H1@KGM1W zIQ-A^Fa0G|3I%I-vkCdnmXg|=$XT8gS)p`}6PPlHNO>3*S1xA*ddhgtj%T{N%gkp; z9a~eiobB(b+0UU*k{vY`S45SyS?ixzg_-z@A&uU zYTI}qevzNpd1Lu8#e9j|dr~>S0b}g_r6cmoqVFxW{)zgod1i)BEDUWdO!+En&J-l9taxMtwAg=lY7V)nU3qp{^?U6$ z!+c4(IlGQa*DaQ=oBu!0;(U3M%%{&kd)74h@#xPp116MZ#}w7){cU4Bzw+ay%XRgR zo@5<);8=h~!ChOc6e0@&AFPr~N_m~#v-JX2 + + + validate.js + + + + + + + + + + +

validate.js

+ +
+

Lightweight JavaScript form validation library inspired by CodeIgniter.

+

No dependencies, just over 1kb gzipped, and customizable!

+ + + validate.js + (development - 10.5kb) + + + + validate.min.js + (minified - 1.3kb) + + +

Example

+ +
All of the fields were successfully validated!
+
+ +
+ + + + + + + + + + + + + + + + + + + +
+ +

Features

+ +
    +
  • Validate form fields from over a dozen rules
  • +
  • No dependencies
  • +
  • Customizable messages
  • +
  • Supply your own validation callbacks for custom rules
  • +
  • Chainable customization methods for ease of declaration
  • +
  • Works in all major browsers (even IE6!)
  • +
  • Modeled off the CodeIgniter form validation API
  • +
+ +

Installation and Usage

+ +
+

Include the JavaScript file in your source

+ +
<script type="text/javascript" src="validate.min.js"></script>
+ +

Create the validation object with your desired rules

+ +
+var validater = new FormValidater('example_form', [{
+    name: 'req',
+    display: 'required',    
+    rules: 'required'
+}, {
+    name: 'alphanumeric',
+    rules: 'alpha_numeric'
+}, {
+    name: 'password',
+    rules: 'required'
+}, {
+    name: 'password_confirm',
+    display: 'password confirmation',
+    rules: 'required|matches[password]'
+}, {
+    name: 'email',
+    rules: 'valid_email'
+}, {
+    name: 'minlength',
+    display: 'min length',
+    rules: 'min_length[8]'
+}], function(errors, events) {
+    if (errors.length > 0) {
+        // Show the errors
+    }
+});
+ +

FormValidater

new FormValidater(formName, fields, callback) + +

The FormValidater object is attached to the window upon loading validate.js. After creation, it will validate the fields on submission of the form named formName.

+ +

The formName passed in to validate must be the exact value of the name attribute of the form

+ +
<form name="example_form"></form>
+ +

An array of fields will be used to perform validation on submission of the form. The array must contain objects containing three properties:

+ +
    +
  • +

    name (required) - The name attribute of the element.

    +
    <input name="email" />
    +
  • +
  • +

    display (optional) - The name of the field as it appears in error messages. If not present in the object, the name parameter will be used.

    +

    Example: If your field name is user, you may choose to use a display of "Username."

    +
  • +
  • +

    rules (required) - One or more rules, which are piped together.

    +

    Example - required|min_length[8]|matches[password_confirm]

    +
  • +
+ +

A callback will always be executed after validation. Your callback should be ready to accept two parameters.

+ +
    +
  • errors - An array of errors from the validation object. If the length > 0, the form failed validation
  • +
  • event - If the browser supports it, the onsubmit event is passed in.
  • +
+ +
function(errors, events) {
+    if (errors.length > 0) {
+        el.innerHTML = errors.join('>br /<');
+    }       
+}        
+        
+
+ +

Custom Validation Rules

+ +
+

validate.js supports the ability for you to include your own validation rules. This will allow you to extend validate.js to suit your needs. A common example of this would be checking if an email is unique.

+ +

First, you need to add another rule to the field. It must always be prefaced with "callback_"

+ +
rules: 'required|callback_check_email'
+ +

Then you must call registerCallback on your instance of the FormValidater with the name of your custom rule and a function taking one parameter. This function will be called with one argument, the value of the field. If the value passes your custom validation, return true, otherwise return false. You can set a message for this rule using the setMessage method as described below.

+ +
validater.registerCallback('email_check', function(value) {
+    if (emailIsUnique(value)) {
+        return true;
+    }
+    
+    return false;
+});
+
+ +

Available Methods

+ +
+

setMessage

validater.setMessage(rule, message) + +

All of the default error messages are located at the top of validate.js in a defaults object. If you wish to change a message application wide, you should do so in the source code. If you would like to change a message for a form, use this method on your instance of the FormValidater object. When setting a new message, you should pass in %s, which will be replaced with the display parameter from the fields array

+ +
validater.setMessage('required', 'You must fill out the %s field.');
+ +

registerCallback

validater.registerCallback(rule, callback) + +

Used to pair a custom rule in the fields array with a callback to be executed upon validation.

+ +
validater.registerCallback('email_check', function(value) {
+    if (emailIsUnique(value)) {
+        return true;
+    }
+    
+    return false;
+});
+
+ +

Available Rules

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
RuleDescriptionParameterExample
requiredreturns false if the form element is empty.no
matchesreturns false if the form element value does not match the one in the parameter.yesmatches[other_element]
valid_emailreturns false if the form element value is not a valid email address.no
min_lengthreturns false if the form element value is shorter than the parameter.yesmin_length[6]
max_lengthreturns false if the form element value is longer than the parameter.yesmax_length[8]
exact_lengthreturns false if the form element value length is not exactly the parameter.yesexact_length[4]
greater_thanreturns false if the form element value length is less than the parameter after using parseFloat.yesgreater_than[10]
less_thanreturns false if the form element value length is greater than the parameter after using parseFloat.yesless_than[2]
alphareturns false if the form element contains anything other than alphabetical characters.no
alpha_numericreturns false if the form element contains anything other than alpha-numeric characters.no
alpha_dashreturns false if the form element contains anything other than alphanumeric characters, underscores, or dashes.no
numericreturns false if the form element contains anything other than numeric characters.no
integerreturns false if the form element contains anything other than an integer.no
+ +

Release Notes

+ +

1.0.0 - 10/17/11

+ +
    +
  • Initial release
  • +
+ +

In Progress

+ +
    +
  • node.js support
  • +
+ +

Contact

+ +

Questions? Need help? Feature request? Let me know on Twitter.

+

Please file issues on GitHub.

+
+ + + +Fork me on GitHub + + + \ No newline at end of file diff --git a/styles/main.css b/styles/main.css new file mode 100644 index 0000000..1718f77 --- /dev/null +++ b/styles/main.css @@ -0,0 +1,324 @@ +/* http://meyerweb.com/eric/tools/css/reset/ + v2.0 | 20110126 + License: none (public domain) +*/ + +html, body, div, span, applet, object, iframe, +h1, h2, h3, h4, h5, h6, p, blockquote, pre, +a, abbr, acronym, address, big, cite, code, +del, dfn, em, img, ins, kbd, q, s, samp, +small, strike, strong, sub, sup, tt, var, +b, u, i, center, +dl, dt, dd, ol, ul, li, +fieldset, form, label, legend, +table, caption, tbody, tfoot, thead, tr, th, td, +article, aside, canvas, details, embed, +figure, figcaption, footer, header, hgroup, +menu, nav, output, ruby, section, summary, +time, mark, audio, video { + margin: 0; + padding: 0; + border: 0; + font-size: 100%; + font: inherit; + vertical-align: baseline; +} +/* HTML5 display-role reset for older browsers */ +article, aside, details, figcaption, figure, +footer, header, hgroup, menu, nav, section { + display: block; +} +body { + line-height: 1; +} +ol, ul { + list-style: none; +} +blockquote, q { + quotes: none; +} +blockquote:before, blockquote:after, +q:before, q:after { + content: ''; + content: none; +} +table { + border-collapse: collapse; + border-spacing: 0; +} +b { + font-weight:bold; +} + +/* Main CSS */ + +body { + background:url('../assets/background.png'); + color:#444; + font:15px 'Helvetica Neue', 'Helvetica', Arial, sans-serif; + margin:30px 100px; +} + +#content { + margin:0 0 0 25px; + width:720px; +} + +#content .bm { + margin-bottom:25px; +} + +h1 { + color:#FF4200; + font:120px 'Andada', 'Helvetica', Arial, sans-serif; + margin:0 0 15px 0; +} + +h2 { + font-size:22px; + font-weight:400; + text-shadow:0px 1px #f8f8f8; +} + +h3 { + clear:both; + color:#FFF; + margin-bottom:20px; +} + +h3 span { + background:#FF4200; + font-size:18px; + padding:5px 10px; +} + +h4 { + float:left; + font-weight:700; + margin-bottom:15px; + margin-right:20px; +} + +.button { + background-color:#0885c7; + background-repeat:repeat-x; + background-image:-khtml-gradient(linear, left top, left bottom, from(#4cbbf5), to(#0885c7)); + background-image:-moz-linear-gradient(top, #4cbbf5, #0885c7); + background-image:-ms-linear-gradient(top, #4cbbf5, #0885c7); + background-image:-webkit-gradient(linear, left top, left bottom, color-stop(0%, #4cbbf5), color-stop(100%, #0885c7)); + background-image:-webkit-linear-gradient(top, #4cbbf5, #0885c7); + background-image:-o-linear-gradient(top, #4cbbf5, #0885c7); + background-image:linear-gradient(top, #4cbbf5, #0885c7); + + border:1px solid #00527d; + border-radius:5px; + -webkit-border-radius:5px; + -moz-border-radius:5px; + + color:#ffffff; + cursor:pointer; + display:block; + float:left; + font-size:20px; + line-height:normal; + padding:10px 15px; + text-align:center; + text-decoration:none; + text-shadow:0 -1px #444444; + + transition:0.2s linear all; + -webkit-transition:0.2s linear all; + -moz-transition:0.2s linear all; + -ms-transition:0.2s linear all; + -o-transition:0.2s linear all; +} + +.button:hover { + background-position:0 -15px; + text-decoration:none; +} + +.button:active { + box-shadow:inset 0 2px 2px rgba(0, 0, 0, 0.25); + -webkit-box-shadow:inset 0 2px 2px rgba(0, 0, 0, 0.25); + -moz-box-shadow:inset 0 2px 2px rgba(0, 0, 0, 0.25); +} + +.button span { + display:block; + font-size:14px; + font-style:italic; +} + +.button.download { + color:#fff; + margin:0 20px 60px 0; +} + +.button.download:hover { + color:#fff; +} + +.button.gray { + background-color: #dcdcdc; + background-repeat: no-repeat; + background-image:-khtml-gradient(linear, left top, left bottom, from(#f2f2f2), to(#dcdcdc)); + background-image:-moz-linear-gradient(top, #f2f2f2, #dcdcdc); + background-image:-ms-linear-gradient(top, #f2f2f2, #dcdcdc); + background-image:-webkit-gradient(linear, left top, left bottom, color-stop(0%, #dcdcdc), color-stop(100%, #dcdcdc)); + background-image:-webkit-linear-gradient(top, #f2f2f2, #dcdcdc); + background-image:-o-linear-gradient(top, #f2f2f2, #dcdcdc); + background-image:linear-gradient(top, #f2f2f2, #dcdcdc); + border:1px solid #444; + color:#444; + font-size:14px; + font-weight:bold; + text-shadow:0px -1px #FFF; +} + +ul { + display:block; + list-style-position:outside; + list-style-type:disc; + margin-left:20px; + margin-bottom:50px; +} + +ul.inline { + margin-bottom:15px; +} + +li { + text-shadow:0px 1px #f8f8f8; +} + +div.section { + margin-bottom:50px; +} + +p { + margin-bottom:10px; + text-shadow:0px 1px #f8f8f8; +} + +/* Form */ + +label, input { + border:0; + display:block; + float:left; + padding:0; + margin:0 30px 5px 0; + width:330px; +} + +input { + background:#f8f8f8; + border:1px solid #444; + border-radius:5px; + -webkit-border-radius:5px; + -moz-border-radius:5px; + margin-bottom:20px; + padding:10px 7px; + width:314px; +} + +input:hover, textarea:hover { + box-shadow:0px 0px 6px #C0C0C0; + -moz-box-shadow:0px 0px 6px #C0C0C0 + -webkit-box-shadow:0px 0px 6px #C0C0C0; +} + +input:focus, textarea:focus { + border:1px solid #0885c7; + outline:none; + box-shadow:0px 0px 12px #C0C0C0; + -moz-box-shadow:0px 0px 12px #C0C0C0 + -webkit-box-shadow:0px 0px 12px #C0C0C0; +} + +button { + clear:both; + margin-bottom:50px; +} + +.error_box { + background:#FAD3C4; + border:1px solid #A75B4E; + border-radius:5px; + -webkit-border-radius:5px; + -moz-border-radius:5px; + color:#444444; + display:none; + font-size:13px; + margin:0px 0px 15px 0px; + padding:8px 8px; + width:672px; +} + +.success_box { + background:#E2F1BB; + border:1px solid #598800; + border-radius:5px; + -webkit-border-radius:5px; + -moz-border-radius:5px; + color:#000000; + display:none; + font-size:13px; + margin:0px 0px 15px 0px; + padding:8px 8px; + width:672px; +} + +/* links */ + +a, a:active, a:visited { + color:#444; + text-decoration:underline; +} + +a:hover { + color:#1F93D0; +} + +/* Tables */ + +table { + margin:35px 0 50px 0; +} + +th { + text-align:left; +} + +th span { + background:#1F93D0; + color:#FFFFFF; + display:block; + float:left; + padding:5px 10px; + margin:0 0 10px 0; +} + +td { + font-size:15px; + padding:0 15px 13px 0; + text-shadow:0px 1px #f8f8f8; +} + +/* Code Formatting */ + +tt, pre { + color:#3c1001; + font:13px Monaco, Consolas, "Lucida Console", monospace; +} + +pre { + border-left:5px solid #0885c7; + margin:0 0 40px 0; + padding:0 0 0 10px; +} + +pre.inline { + margin:0 0 15px 0; +} From dc1e75a6dfb8536c259c5c53a69ddee66e1f12a2 Mon Sep 17 00:00:00 2001 From: Rick Harrison Date: Mon, 17 Oct 2011 00:00:05 -0700 Subject: [PATCH 03/40] Added the minified version. --- index.html | 2 +- validate.min.js | 16 ++++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) create mode 100644 validate.min.js diff --git a/index.html b/index.html index d072d16..3491cb4 100644 --- a/index.html +++ b/index.html @@ -9,7 +9,7 @@ - +

validate.js

diff --git a/validate.min.js b/validate.min.js new file mode 100644 index 0000000..2966c8f --- /dev/null +++ b/validate.min.js @@ -0,0 +1,16 @@ +/* + * validate.js 1.0.0 + * Copyright (c) 2011 Rick Harrison, http://rickharrison.me + * validate.js is open sourced under the MIT license. + * Portions of validate.js are inspired by CodeIgniter. + * http://rickharrison.github.com/validate.js + */ + +(function(j,k,i){var l={required:"The %s field is required.",matches:"The %s field does not match the %s field.",valid_email:"The %s field must contain a valid email address.",min_length:"The %s field must be at least %s characters in length.",max_length:"The %s field must not exceed %s characters in length.",exact_length:"The %s field must be exactly %s characters in length.",greater_than:"The %s field must contain a number greater than %s.",less_than:"The %s field must contain a number less than %s.", +alpha:"The %s field must only contain alphabetical characters.",alpha_numeric:"The %s field must only contain alpha-numeric characters.",alpha_dash:"The %s field must only contain alpha-numeric characters, underscores, and dashes.",numeric:"The %s field must contain only numbers.",integer:"The %s field must contain an integer."},m=function(){},n=/^(.+)\[(.+)\]$/,g=/^[0-9]+$/,o=/^\-?[0-9]+$/,h=/^\-?[0-9]*\.?[0-9]+$/,p=/^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,6}$/i,q=/^[a-z]+$/i,r=/^[a-z0-9]+$/i,s=/^[a-z0-9_-]+$/i, +e=function(a,b,d){this.callback=d||m;this.errors=[];this.fields={};this.form=k.forms[a]||{};this.messages={};this.handlers={};a=0;for(d=b.length;a0)if(a&&a.preventDefault)a.preventDefault();else return false;return true};e.prototype._validateField= +function(a){var b=a.rules.split("|");if(!(a.rules.indexOf("required")===-1&&(!a.value||a.value===""||a.value===i)))for(var d=0,c=b.length;d=b},max_length:function(a,b){return!g.test(b)? +false:a.value.length<=b},exact_length:function(a,b){return!g.test(b)?false:a.value.length==b},greater_than:function(a,b){return!h.test(a.value)?false:parseFloat(a.value)>parseFloat(b)},less_than:function(a,b){return!h.test(a.value)?false:parseFloat(a.value) Date: Mon, 17 Oct 2011 00:04:52 -0700 Subject: [PATCH 04/40] Changed some of the list styling. --- styles/main.css | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/styles/main.css b/styles/main.css index 1718f77..f8663a6 100644 --- a/styles/main.css +++ b/styles/main.css @@ -181,7 +181,7 @@ ul { list-style-position:outside; list-style-type:disc; margin-left:20px; - margin-bottom:50px; + margin-bottom:40px; } ul.inline { From c6e9696e2000d2ade7ed99122f10a80234e60ada Mon Sep 17 00:00:00 2001 From: Rick Harrison Date: Mon, 17 Oct 2011 09:50:09 -0700 Subject: [PATCH 05/40] Fixed a typo in a code sample. --- index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/index.html b/index.html index 3491cb4..d1cf2a9 100644 --- a/index.html +++ b/index.html @@ -138,7 +138,7 @@

FormValidater

new FormValidater(formName, fields, callback)
function(errors, events) {
     if (errors.length > 0) {
-        el.innerHTML = errors.join('>br /<');
+        el.innerHTML = errors.join('<br />');
     }       
 }        
         
From e037a47a3296f0bf55e76fbcc3c5b0f68727b4cf Mon Sep 17 00:00:00 2001 From: Rick Harrison Date: Mon, 17 Oct 2011 09:51:29 -0700 Subject: [PATCH 06/40] Added some info about how to call setMessage. --- index.html | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/index.html b/index.html index d1cf2a9..c3ae1c4 100644 --- a/index.html +++ b/index.html @@ -161,7 +161,8 @@

Custom Validation Rules

} return false; -}); +}) +.setMessage('email_check', 'That email is already taken. Please choose another.');

Available Methods

From c3e8e61679694e5c9602e939f1ee65ace48bac7d Mon Sep 17 00:00:00 2001 From: Rick Harrison Date: Mon, 17 Oct 2011 09:54:04 -0700 Subject: [PATCH 07/40] Fixed a few typos. --- index.html | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/index.html b/index.html index c3ae1c4..bcb4a2c 100644 --- a/index.html +++ b/index.html @@ -172,7 +172,7 @@

setMessage

validater.setMessage(rule, message)

All of the default error messages are located at the top of validate.js in a defaults object. If you wish to change a message application wide, you should do so in the source code. If you would like to change a message for a form, use this method on your instance of the FormValidater object. When setting a new message, you should pass in %s, which will be replaced with the display parameter from the fields array

-
validater.setMessage('required', 'You must fill out the %s field.');
+
validater.setMessage('required', 'You must fill out the %s field.');

registerCallback

validater.registerCallback(rule, callback) @@ -243,14 +243,14 @@

Available Rules

greater_than - returns false if the form element value length is less than the parameter after using parseFloat. + returns false if the form element value is less than the parameter after using parseFloat. yes greater_than[10] less_than - returns false if the form element value length is greater than the parameter after using parseFloat. + returns false if the form element value is greater than the parameter after using parseFloat. yes less_than[2] From 612370925835e899121ae1d7f81441cce56289b5 Mon Sep 17 00:00:00 2001 From: Rick Harrison Date: Mon, 17 Oct 2011 10:26:40 -0700 Subject: [PATCH 08/40] Added google analytics. --- index.html | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/index.html b/index.html index bcb4a2c..4d3dfe1 100644 --- a/index.html +++ b/index.html @@ -361,5 +361,19 @@

Contact

Fork me on GitHub + + \ No newline at end of file From 35da47edbdb00d68fb0dc3bc05f7c89355f6a15a Mon Sep 17 00:00:00 2001 From: treyp Date: Mon, 17 Oct 2011 12:40:11 -0500 Subject: [PATCH 09/40] Adding IDs to the example input elements so that the labels work correctly for them --- index.html | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/index.html b/index.html index 4d3dfe1..a4851b6 100644 --- a/index.html +++ b/index.html @@ -37,20 +37,20 @@

Example

- - + + - - + + - - + + From 1c43b40247db57c915c8925251e137f388c1dbb2 Mon Sep 17 00:00:00 2001 From: Rick Harrison Date: Mon, 17 Oct 2011 10:40:49 -0700 Subject: [PATCH 10/40] Changed everything to FormValidator. --- index.html | 28 +++++++++++++++++----------- validate.min.js | 4 ++-- 2 files changed, 19 insertions(+), 13 deletions(-) diff --git a/index.html b/index.html index 4d3dfe1..a8a03bb 100644 --- a/index.html +++ b/index.html @@ -77,7 +77,7 @@

Installation and Usage

Create the validation object with your desired rules

-var validater = new FormValidater('example_form', [{
+var validator = new FormValidator('example_form', [{
     name: 'req',
     display: 'required',    
     rules: 'required'
@@ -104,9 +104,9 @@ 

Installation and Usage

} });
-

FormValidater

new FormValidater(formName, fields, callback) +

FormValidator

new FormValidator(formName, fields, callback) -

The FormValidater object is attached to the window upon loading validate.js. After creation, it will validate the fields on submission of the form named formName.

+

The FormValidator object is attached to the window upon loading validate.js. After creation, it will validate the fields on submission of the form named formName.

The formName passed in to validate must be the exact value of the name attribute of the form

@@ -153,9 +153,9 @@

Custom Validation Rules

rules: 'required|callback_check_email'
-

Then you must call registerCallback on your instance of the FormValidater with the name of your custom rule and a function taking one parameter. This function will be called with one argument, the value of the field. If the value passes your custom validation, return true, otherwise return false. You can set a message for this rule using the setMessage method as described below.

+

Then you must call registerCallback on your instance of the FormValidator with the name of your custom rule and a function taking one parameter. This function will be called with one argument, the value of the field. If the value passes your custom validation, return true, otherwise return false. You can set a message for this rule using the setMessage method as described below.

-
validater.registerCallback('email_check', function(value) {
+        
validator.registerCallback('email_check', function(value) {
     if (emailIsUnique(value)) {
         return true;
     }
@@ -168,17 +168,17 @@ 

Custom Validation Rules

Available Methods

-

setMessage

validater.setMessage(rule, message) +

setMessage

validator.setMessage(rule, message) -

All of the default error messages are located at the top of validate.js in a defaults object. If you wish to change a message application wide, you should do so in the source code. If you would like to change a message for a form, use this method on your instance of the FormValidater object. When setting a new message, you should pass in %s, which will be replaced with the display parameter from the fields array

+

All of the default error messages are located at the top of validate.js in a defaults object. If you wish to change a message application wide, you should do so in the source code. If you would like to change a message for a form, use this method on your instance of the FormValidator object. When setting a new message, you should pass in %s, which will be replaced with the display parameter from the fields array

-
validater.setMessage('required', 'You must fill out the %s field.');
+
validator.setMessage('required', 'You must fill out the %s field.');
-

registerCallback

validater.registerCallback(rule, callback) +

registerCallback

validator.registerCallback(rule, callback)

Used to pair a custom rule in the fields array with a callback to be executed upon validation.

-
validater.registerCallback('email_check', function(value) {
+        
validator.registerCallback('email_check', function(value) {
     if (emailIsUnique(value)) {
         return true;
     }
@@ -294,6 +294,12 @@ 

Available Rules

Release Notes

+

1.0.1 - 10/17/11

+ +
    +
  • Renamed FormValidater to FormValidator
  • +
+

1.0.0 - 10/17/11

    @@ -314,7 +320,7 @@

    Contact

    -Fork me on GitHub +Fork me on GitHub - \ No newline at end of file + From c4426f1df8447108cb9611bcf93589a33cc5f245 Mon Sep 17 00:00:00 2001 From: Scott Luptowski Date: Sun, 6 Apr 2014 12:42:30 -0400 Subject: [PATCH 34/40] Added documentation for conditional field validation --- README.md | 6 +++++- index.html | 29 +++++++++++++++++++++++++++-- 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 502e76b..259d679 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,7 @@ validate.js is a lightweight JavaScript form validation library inspired by Code - Customizable Messages - Supply your own validation callbacks for custom rules - Chainable customization methods for ease of declaration +- Conditionally validate certain form fields - Works in all major browsers, (even IE6!) - Modeled off the CodeIgniter form validation API @@ -30,7 +31,10 @@ validate.js is a lightweight JavaScript form validation library inspired by Code rules: 'required|matches[password]' }, { name: 'email', - rules: 'valid_email' + rules: 'valid_email', + depends: function() { + return Math.random() > .5; + } }, { name: 'minlength', display: 'min length', diff --git a/index.html b/index.html index b88a15f..40409a9 100644 --- a/index.html +++ b/index.html @@ -71,6 +71,7 @@

    Features

  • Customizable messages
  • Supply your own validation callbacks for custom rules
  • Chainable customization methods for ease of declaration
  • +
  • Conditionally validate certain form fields
  • Works in all major browsers (even IE6!)
  • Modeled off the CodeIgniter form validation API
@@ -101,7 +102,10 @@

Installation and Usage

rules: 'required|matches[password]' }, { name: 'email', - rules: 'valid_email' + rules: 'valid_email', + depends: function() { + return Math.random() > .5; + } }, { name: 'minlength', display: 'min length', @@ -120,7 +124,7 @@

FormValidator

new FormValidator(formName, fields, callback)
<form name="example_form"></form>
-

An array of fields will be used to perform validation on submission of the form. The array must contain objects containing three properties:

+

An array of fields will be used to perform validation on submission of the form. The array must contain objects containing these properties:

  • @@ -135,6 +139,13 @@

    FormValidator

    new FormValidator(formName, fields, callback)

    rules (required) - One or more rules, which are piped together.

    Example - required|min_length[8]|matches[password_confirm]

  • +
  • +

    depends (optional) - An function that runs before the field is validated. If the function returns false, the field is never validated against the declared rules.

    +
    depends: function(field) {
    +            return Math.random() > .5;
    +}
    +                
    +

A callback will always be executed after validation. Your callback should be ready to accept two parameters.

@@ -212,6 +223,20 @@

registerCallback

validator.registerCallback(rule, callback) return false; });
+ +

registerConditional

validator.registerConditional(name, callback) + +

An alternate syntax for declaring depends functions, which determine whether or not to validate a given field. + +

{
+    name: 'first_name',
+    rules: 'required',
+    depends: 'checkForRandomNumber'
+}
+ +
validator.registerConditional('checkForRandomNumber', function(field) {
+    return Math.random() > .5;
+});

Available Rules

From 53f0a80aa1979df579c10f01a9865713c9626400 Mon Sep 17 00:00:00 2001 From: Rick Harrison Date: Sun, 13 Apr 2014 16:40:00 -0700 Subject: [PATCH 35/40] Updated styling on depends docs. --- index.html | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/index.html b/index.html index 9987cfe..eaf11a8 100644 --- a/index.html +++ b/index.html @@ -140,11 +140,10 @@

FormValidator

new FormValidator(formName, fields, callback)

Example - required|min_length[8]|matches[password_confirm]

  • -

    depends (optional) - An function that runs before the field is validated. If the function returns false, the field is never validated against the declared rules.

    +

    depends (optional) - A function that runs before the field is validated. If the function returns false, the field is never validated against the declared rules.

    depends: function(field) {
    -            return Math.random() > .5;
    -}
    -                
    + return Math.random() > .5; +}
  • @@ -172,8 +171,7 @@

    FormValidator

    new FormValidator(formName, fields, callback) el.innerHTML = errorString; } -} -
    +}

    Custom Validation Rules

    @@ -216,7 +214,7 @@

    registerCallback

    validator.registerCallback(rule, callback)

    Used to pair a custom rule in the fields array with a callback to be executed upon validation.

    -
    validator.registerCallback('check_email', function(value) {
    +        
    validator.registerCallback('check_email', function(value) {
         if (emailIsUnique(value)) {
             return true;
         }
    
    From eb447d3b4b6fcafc10156d1c5abb30b22e26d2ab Mon Sep 17 00:00:00 2001
    From: Rick Harrison 
    Date: Sun, 13 Apr 2014 16:51:23 -0700
    Subject: [PATCH 36/40] Updated to version 1.4
    
    ---
     LICENSE         |  2 +-
     index.html      |  6 ++++++
     validate.js     | 46 +++++++++++++++++++++++++++++++++++++---------
     validate.min.js |  6 +++---
     4 files changed, 47 insertions(+), 13 deletions(-)
    
    diff --git a/LICENSE b/LICENSE
    index c0f378e..1d62568 100644
    --- a/LICENSE
    +++ b/LICENSE
    @@ -4,7 +4,7 @@ The text of this license is provided below:
     MIT License
     -----------
     
    -Copyright (C) 2011 - 2013 by Rick Harrison, http://rickharrison.me
    +Copyright (C) 2011 - 2014 by Rick Harrison, http://rickharrison.me
     
     Permission is hereby granted, free of charge, to any person obtaining a copy
     of this software and associated documentation files (the "Software"), to deal
    diff --git a/index.html b/index.html
    index eaf11a8..8d58cf1 100644
    --- a/index.html
    +++ b/index.html
    @@ -407,6 +407,12 @@ 

    Available Rules

    Release Notes

    +

    1.4 - 04/13/14

    + +
      +
    • Added `depends` for conditional validation.
    • +
    +

    1.3 - 08/18/13

      diff --git a/validate.js b/validate.js index aa33228..0071382 100644 --- a/validate.js +++ b/validate.js @@ -1,6 +1,6 @@ /* - * validate.js 1.3 - * Copyright (c) 2013 Rick Harrison, http://rickharrison.me + * validate.js 1.4 + * Copyright (c) 2011 - 2014 Rick Harrison, http://rickharrison.me * validate.js is open sourced under the MIT license. * Portions of validate.js are inspired by CodeIgniter. * http://rickharrison.github.com/validate.js @@ -83,6 +83,7 @@ this.form = this._formByNameOrNode(formNameOrNode) || {}; this.messages = {}; this.handlers = {}; + this.conditionals = {}; for (var i = 0, fieldLength = fields.length; i < fieldLength; i++) { var field = fields[i]; @@ -97,7 +98,7 @@ */ if (field.names) { - for (var j = 0; j < field.names.length; j++) { + for (var j = 0, fieldNamesLength = field.names.length; j < fieldNamesLength; j++) { this._addField(field, field.names[j]); } } else { @@ -124,7 +125,7 @@ var i; if ((element.length > 0) && (element[0].type === 'radio' || element[0].type === 'checkbox')) { - for (i = 0; i < element.length; i++) { + for (i = 0, elementLength = element.length; i < elementLength; i++) { if (element[i].checked) { return element[i][attributeName]; } @@ -162,6 +163,20 @@ return this; }; + /* + * @public + * Registers a conditional for a custom 'depends' rule + */ + + FormValidator.prototype.registerConditional = function(name, conditional) { + if (name && typeof name === 'string' && conditional && typeof conditional === 'function') { + this.conditionals[name] = conditional; + } + + // return this for chaining + return this; + }; + /* * @private * Determines if a form dom node was passed in or just a string representing the form name @@ -181,6 +196,7 @@ name: nameValue, display: field.display || nameValue, rules: field.rules, + depends: field.depends, id: null, type: null, value: null, @@ -209,9 +225,21 @@ /* * Run through the rules for each field. + * If the field has a depends conditional, only validate the field + * if it passes the custom function */ - this._validateField(field); + if (field.depends && typeof field.depends === "function") { + if (field.depends.call(this, field)) { + this._validateField(field); + } + } else if (field.depends && typeof field.depends === "string" && this.conditionals[field.depends]) { + if (this.conditionals[field.depends].call(this,field)) { + this._validateField(field); + } + } else { + this._validateField(field); + } } } } @@ -269,7 +297,7 @@ method = parts[1]; param = parts[2]; } - + if (method.charAt(0) === '!') { method = method.substring(1, method.length); } @@ -299,7 +327,7 @@ if (failed) { // Make sure we have a message for this rule - var source = this.messages[method] || defaults.messages[method], + var source = this.messages[field.name + '.' + method] || this.messages[method] || defaults.messages[method], message = 'An error has occurred with the ' + field.display + ' field.'; if (source) { @@ -338,7 +366,7 @@ return (value !== null && value !== ''); }, - + "default": function(field, defaultName){ return field.value !== defaultName; }, @@ -360,7 +388,7 @@ valid_emails: function(field) { var result = field.value.split(","); - for (var i = 0; i < result.length; i++) { + for (var i = 0, resultLength = result.length; i < resultLength; i++) { if (!emailRegex.test(result[i])) { return false; } diff --git a/validate.min.js b/validate.min.js index f8c569e..02c2f2f 100644 --- a/validate.min.js +++ b/validate.min.js @@ -1,9 +1,9 @@ /* - * validate.js 1.3 - * Copyright (c) 2013 Rick Harrison, http://rickharrison.me + * validate.js 1.4 + * Copyright (c) 2011 - 2014 Rick Harrison, http://rickharrison.me * validate.js is open sourced under the MIT license. * Portions of validate.js are inspired by CodeIgniter. * http://rickharrison.github.com/validate.js */ -(function(q,r,m){var s={required:"The %s field is required.",matches:"The %s field does not match the %s field.","default":"The %s field is still set to default, please change.",valid_email:"The %s field must contain a valid email address.",valid_emails:"The %s field must contain all valid email addresses.",min_length:"The %s field must be at least %s characters in length.",max_length:"The %s field must not exceed %s characters in length.",exact_length:"The %s field must be exactly %s characters in length.",greater_than:"The %s field must contain a number greater than %s.",less_than:"The %s field must contain a number less than %s.",alpha:"The %s field must only contain alphabetical characters.",alpha_numeric:"The %s field must only contain alpha-numeric characters.",alpha_dash:"The %s field must only contain alpha-numeric characters, underscores, and dashes.",numeric:"The %s field must contain only numbers.",integer:"The %s field must contain an integer.",decimal:"The %s field must contain a decimal number.",is_natural:"The %s field must contain only positive numbers.",is_natural_no_zero:"The %s field must contain a number greater than zero.",valid_ip:"The %s field must contain a valid IP.",valid_base64:"The %s field must contain a base64 string.",valid_credit_card:"The %s field must contain a valid credit card number.",is_file_type:"The %s field must contain only %s files.",valid_url:"The %s field must contain a valid URL."},t=function(a){},u=/^(.+?)\[(.+)\]$/,h=/^[0-9]+$/,v=/^\-?[0-9]+$/,k=/^\-?[0-9]*\.?[0-9]+$/,p=/^[a-zA-Z0-9.!#$%&'*+\-\/=?\^_`{|}~\-]+@[a-zA-Z0-9\-]+(?:\.[a-zA-Z0-9\-]+)*$/,w=/^[a-z]+$/i,x=/^[a-z0-9]+$/i,y=/^[a-z0-9_\-]+$/i,z=/^[0-9]+$/i,A=/^[1-9][0-9]*$/i,B=/^((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){3}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})$/i,C=/[^a-zA-Z0-9\/\+=]/i,D=/^[\d\-\s]+$/,E=/^((http|https):\/\/(\w+:{0,1}\w*@)?(\S+)|)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/,e=function(a,b,c){this.callback=c||t;this.errors=[];this.fields={};this.form=this._formByNameOrNode(a)||{};this.messages={};this.handlers={};a=0;for(c=b.length;a=parseInt(b,10):!1},max_length:function(a,b){return h.test(b)?a.value.length<=parseInt(b,10):!1},exact_length:function(a,b){return h.test(b)?a.value.length===parseInt(b,10):!1},greater_than:function(a,b){return k.test(a.value)?parseFloat(a.value)>parseFloat(b):!1},less_than:function(a,b){return k.test(a.value)?parseFloat(a.value)0&&(e[0].type==="radio"||e[0].type==="checkbox")){for(a=0,elementLength=e.length;a0?n[0].type:n.type;i.value=y(n,"value");i.checked=y(n,"checked");if(i.depends&&typeof i.depends==="function"){if(i.depends.call(this,i)){this._validateField(i)}}else if(i.depends&&typeof i.depends==="string"&&this.conditionals[i.depends]){if(this.conditionals[i.depends].call(this,i)){this._validateField(i)}}else{this._validateField(i)}}}}if(typeof this.callback==="function"){this.callback(this.errors,e)}if(this.errors.length>0){if(e&&e.preventDefault){e.preventDefault()}else if(event){event.returnValue=false}}return true};g.prototype._validateField=function(e){var t=e.rules.split("|"),s=e.rules.indexOf("required"),r=!e.value||e.value===""||e.value===a;for(var l=0,u=t.length;l=parseInt(t,10)},max_length:function(e,t){if(!s.test(t)){return false}return e.value.length<=parseInt(t,10)},exact_length:function(e,t){if(!s.test(t)){return false}return e.value.length===parseInt(t,10)},greater_than:function(e,t){if(!l.test(e.value)){return false}return parseFloat(e.value)>parseFloat(t)},less_than:function(e,t){if(!l.test(e.value)){return false}return parseFloat(e.value)=0;s--){var r=n.charAt(s);a=parseInt(r,10);if(i){if((a*=2)>9)a-=9}t+=a;i=!i}return t%10===0},is_file_type:function(e,t){if(e.type!=="file"){return true}var a=e.value.substr(e.value.lastIndexOf(".")+1),i=t.split(","),n=false,s=0,r=i.length;for(s;s Date: Wed, 20 Aug 2014 14:14:34 -0700 Subject: [PATCH 37/40] Updated to 1.4.1 --- index.html | 182 +++++++++++++++++++++++++----------------------- validate.js | 9 ++- validate.min.js | 16 ++++- 3 files changed, 114 insertions(+), 93 deletions(-) diff --git a/index.html b/index.html index 8d58cf1..537efa9 100644 --- a/index.html +++ b/index.html @@ -2,12 +2,12 @@ validate.js - + - + - + @@ -17,54 +17,54 @@

      validate.js

      Lightweight JavaScript form validation library inspired by CodeIgniter.

      No dependencies, just over 2kb gzipped, and customizable!

      - + validate.js (development - 16kb) - + validate.min.js (minified - 2.1kb)
      - + - + - +

      Example

      - +
      All of the fields were successfully validated!
      - +
      - + - + - + - + - + - + - +
      - +

      Features

      - +
      • Validate form fields from over a dozen rules
      • No dependencies
      • @@ -75,20 +75,20 @@

        Features

      • Works in all major browsers (even IE6!)
      • Modeled off the CodeIgniter form validation API
      - +

      Installation and Usage

      - +

      Include the JavaScript file in your source

      - +
      <script type="text/javascript" src="validate.min.js"></script>
      - +

      Create the validation object with your desired rules. This needs to be in a <script> tag located just before your closing </body> tag. The reason for this being that the DOM needs to have your form loaded before you can attach your rules.

      - +
       var validator = new FormValidator('example_form', [{
           name: 'req',
      -    display: 'required',    
      +    display: 'required',
           rules: 'required'
       }, {
           name: 'alphanumeric',
      @@ -115,17 +115,17 @@ 

      Installation and Usage

      // Show the errors } });
      - +

      FormValidator

      new FormValidator(formName, fields, callback) - +

      The FormValidator object is attached to the window upon loading validate.js. After creation, it will validate the fields on submission of the form named formName.

      - +

      The formName passed in to validate must be the exact value of the name attribute of the form

      - +
      <form name="example_form"></form>
      - +

      An array of fields will be used to perform validation on submission of the form. The array must contain objects containing these properties:

      - +
      • name (required) - The name attribute of the element.

        @@ -146,9 +146,9 @@

        FormValidator

        new FormValidator(formName, fields, callback) }
    - +

    A callback will always be executed after validation. Your callback should be ready to accept two parameters.

    - +
    • errors - An array of errors from the validation object. If the length > 0, the form failed validation

      @@ -160,36 +160,36 @@

      FormValidator

      new FormValidator(formName, fields, callback)
    • event - If the browser supports it, the onsubmit event is passed in.
    - +
    function(errors, event) {
         if (errors.length > 0) {
             var errorString = '';
    -        
    +
             for (var i = 0, errorLength = errors.length; i < errorLength; i++) {
                 errorString += errors[i].message + '<br />';
             }
    -        
    +
             el.innerHTML = errorString;
    -    }       
    +    }
     }
    - +

    Custom Validation Rules

    - +

    validate.js supports the ability for you to include your own validation rules. This will allow you to extend validate.js to suit your needs. A common example of this would be checking the strength of a password.

    - +

    First, you need to add another rule to the field. It must always be prefaced with "callback_"

    - +
    rules: 'required|callback_check_password'
    - +

    Then you must call registerCallback on your instance of the FormValidator with the name of your custom rule and a function taking one parameter. This function will be called with one argument, the value of the field. If the value passes your custom validation, return true, otherwise return false. You can set a message for this rule using the setMessage method as described below.

    - +
    validator.registerCallback('check_password', function(value) {
         if (passwordIsStrong(value)) {
             return true;
         }
    -    
    +
         return false;
     })
     .setMessage('check_password', 'Please choose a stronger password using at least 1 number.');
    @@ -200,25 +200,25 @@

    Custom Validation Rules

    #3. A callback will always be called if it is preceded by an '!' i.e. rules: '!callback_myCustomCallback'

    - +

    Available Methods

    - +

    setMessage

    validator.setMessage(rule, message) - +

    All of the default error messages are located at the top of validate.js in a defaults object. If you wish to change a message application wide, you should do so in the source code. If you would like to change a message for a form, use this method on your instance of the FormValidator object. When setting a new message, you should pass in %s, which will be replaced with the display parameter from the fields array

    - +
    validator.setMessage('required', 'You must fill out the %s field.');
    - +

    registerCallback

    validator.registerCallback(rule, callback) - +

    Used to pair a custom rule in the fields array with a callback to be executed upon validation.

    - +
    validator.registerCallback('check_email', function(value) {
         if (emailIsUnique(value)) {
             return true;
         }
    -    
    +
         return false;
     });
    @@ -236,9 +236,9 @@

    registerConditional

    validator.registerConditional(name, callback) .5; });
    - +

    Available Rules

    - + @@ -255,14 +255,14 @@

    Available Rules

    - + - + @@ -283,63 +283,63 @@

    Available Rules

    - + - + - + - + - + - + - + - + - + @@ -381,7 +381,7 @@

    Available Rules

    - + @@ -395,7 +395,7 @@

    Available Rules

    - + @@ -404,9 +404,15 @@

    Available Rules

    no
    matches returns false if the form element value does not match the one in the parameter. yes matches[other_element]
    valid_email returns false if the form element value is not a valid email address. yes min_length[6]
    max_length returns false if the form element value is longer than the parameter. yes max_length[8]
    exact_length returns false if the form element value length is not exactly the parameter. yes exact_length[4]
    greater_than returns false if the form element value is less than the parameter after using parseFloat. yes greater_than[10]
    less_than returns false if the form element value is greater than the parameter after using parseFloat. yes less_than[2]
    alpha returns false if the form element contains anything other than alphabetical characters. no
    alpha_numeric returns false if the form element contains anything other than alpha-numeric characters. no
    alpha_dash returns false if the form element contains anything other than alphanumeric characters, underscores, or dashes. no
    numeric returns false if the form element contains anything other than numeric characters. no
    integer returns false if the form element contains anything other than an integer. no
    valid_credit_card returns false if the supplied string is not a valid credit card no
    is_file_type returns false if the supplied file is not part of the comma separated list in the paramter
    - +

    Release Notes

    +

    1.4.1 - 08/20/14

    + +
      +
    • Updated email regex to html 5 specificiation.
    • +
    +

    1.4 - 04/13/14

      @@ -431,13 +437,13 @@

      1.2.2 - 03/27/13

    1.2.1 - 03/17/13

    - +
    • Added valid_url rule - contributed by tajo
    - +

    1.2 - 01/20/13

    - +
    • Added radio button support - contributed by ikr
    • Added is_file_type rule - contributed by tricinel
    • @@ -445,9 +451,9 @@

      1.2 - 01/20/13

    • Added the rule to the errors array in the callback - contributed by jhnns
    • Added valid_credit_card rule - contributed by grahamhayes
    - +

    1.1 - 05/17/12

    - +
    • Changed the format of the error parameter in the validation callback.

      @@ -457,34 +463,34 @@

      1.1 - 05/17/12

      - message: The error message to display

    - +

    1.0.2 - 12/19/11

    - +
    • Added new rules: valid_emails, decimal, is_natural, is_natural_no_zero, valid_ip, valid_base64
    • Bug fixes
    - +

    1.0.1 - 10/17/11

    - +
    • Minor bug fixes
    - +

    1.0.0 - 10/17/11

    - +
    • Initial release
    - +

    In Progress

    - +
    • node.js support
    - +

    Contact

    - +

    Questions? Need help? Feature request? Let me know on Twitter.

    Please file issues on GitHub.

    @@ -494,7 +500,7 @@

    Contact

    new FormValidator('example_form', [{ name: 'req', - display: 'required', + display: 'required', rules: 'required' }, { name: 'alphanumeric', @@ -526,21 +532,21 @@

    Contact

    var SELECTOR_ERRORS = $('.error_box'), SELECTOR_SUCCESS = $('.success_box'); - + if (errors.length > 0) { SELECTOR_ERRORS.empty(); - + for (var i = 0, errorLength = errors.length; i < errorLength; i++) { SELECTOR_ERRORS.append(errors[i].message + '
    '); } - + SELECTOR_SUCCESS.css({ display: 'none' }); SELECTOR_ERRORS.fadeIn(200); } else { SELECTOR_ERRORS.css({ display: 'none' }); SELECTOR_SUCCESS.fadeIn(200); } - + if (evt && evt.preventDefault) { evt.preventDefault(); } else if (event) { diff --git a/validate.js b/validate.js index 0071382..14c6f05 100644 --- a/validate.js +++ b/validate.js @@ -1,5 +1,5 @@ /* - * validate.js 1.4 + * validate.js 1.4.1 * Copyright (c) 2011 - 2014 Rick Harrison, http://rickharrison.me * validate.js is open sourced under the MIT license. * Portions of validate.js are inspired by CodeIgniter. @@ -51,7 +51,7 @@ numericRegex = /^[0-9]+$/, integerRegex = /^\-?[0-9]+$/, decimalRegex = /^\-?[0-9]*\.?[0-9]+$/, - emailRegex = /^[a-zA-Z0-9.!#$%&'*+\-\/=?\^_`{|}~\-]+@[a-zA-Z0-9\-]+(?:\.[a-zA-Z0-9\-]+)*$/, + emailRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/, alphaRegex = /^[a-z]+$/i, alphaNumericRegex = /^[a-z0-9]+$/i, alphaDashRegex = /^[a-z0-9_\-]+$/i, @@ -198,6 +198,7 @@ rules: field.rules, depends: field.depends, id: null, + element: null, type: null, value: null, checked: null @@ -219,6 +220,7 @@ if (element && element !== undefined) { field.id = attributeValue(element, 'id'); + field.element = element; field.type = (element.length > 0) ? element[0].type : element.type; field.value = attributeValue(element, 'value'); field.checked = attributeValue(element, 'checked'); @@ -315,7 +317,7 @@ method = method.substring(9, method.length); if (typeof this.handlers[method] === 'function') { - if (this.handlers[method].apply(this, [field.value, param]) === false) { + if (this.handlers[method].apply(this, [field.value, param, field]) === false) { failed = true; } } @@ -340,6 +342,7 @@ this.errors.push({ id: field.id, + element: field.element, name: field.name, message: message, rule: method diff --git a/validate.min.js b/validate.min.js index 02c2f2f..bd0d845 100644 --- a/validate.min.js +++ b/validate.min.js @@ -1,9 +1,21 @@ /* - * validate.js 1.4 + * validate.js 1.4.1 * Copyright (c) 2011 - 2014 Rick Harrison, http://rickharrison.me * validate.js is open sourced under the MIT license. * Portions of validate.js are inspired by CodeIgniter. * http://rickharrison.github.com/validate.js */ -(function(e,t,a){var i={messages:{required:"The %s field is required.",matches:"The %s field does not match the %s field.","default":"The %s field is still set to default, please change.",valid_email:"The %s field must contain a valid email address.",valid_emails:"The %s field must contain all valid email addresses.",min_length:"The %s field must be at least %s characters in length.",max_length:"The %s field must not exceed %s characters in length.",exact_length:"The %s field must be exactly %s characters in length.",greater_than:"The %s field must contain a number greater than %s.",less_than:"The %s field must contain a number less than %s.",alpha:"The %s field must only contain alphabetical characters.",alpha_numeric:"The %s field must only contain alpha-numeric characters.",alpha_dash:"The %s field must only contain alpha-numeric characters, underscores, and dashes.",numeric:"The %s field must contain only numbers.",integer:"The %s field must contain an integer.",decimal:"The %s field must contain a decimal number.",is_natural:"The %s field must contain only positive numbers.",is_natural_no_zero:"The %s field must contain a number greater than zero.",valid_ip:"The %s field must contain a valid IP.",valid_base64:"The %s field must contain a base64 string.",valid_credit_card:"The %s field must contain a valid credit card number.",is_file_type:"The %s field must contain only %s files.",valid_url:"The %s field must contain a valid URL."},callback:function(e){}};var n=/^(.+?)\[(.+)\]$/,s=/^[0-9]+$/,r=/^\-?[0-9]+$/,l=/^\-?[0-9]*\.?[0-9]+$/,u=/^[a-zA-Z0-9.!#$%&'*+\-\/=?\^_`{|}~\-]+@[a-zA-Z0-9\-]+(?:\.[a-zA-Z0-9\-]+)*$/,f=/^[a-z]+$/i,o=/^[a-z0-9]+$/i,h=/^[a-z0-9_\-]+$/i,d=/^[0-9]+$/i,c=/^[1-9][0-9]*$/i,p=/^((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){3}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})$/i,m=/[^a-zA-Z0-9\/\+=]/i,v=/^[\d\-\s]+$/,_=/^((http|https):\/\/(\w+:{0,1}\w*@)?(\S+)|)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/;var g=function(e,t,n){this.callback=n||i.callback;this.errors=[];this.fields={};this.form=this._formByNameOrNode(e)||{};this.messages={};this.handlers={};this.conditionals={};for(var s=0,r=t.length;s0&&(e[0].type==="radio"||e[0].type==="checkbox")){for(a=0,elementLength=e.length;a0?n[0].type:n.type;i.value=y(n,"value");i.checked=y(n,"checked");if(i.depends&&typeof i.depends==="function"){if(i.depends.call(this,i)){this._validateField(i)}}else if(i.depends&&typeof i.depends==="string"&&this.conditionals[i.depends]){if(this.conditionals[i.depends].call(this,i)){this._validateField(i)}}else{this._validateField(i)}}}}if(typeof this.callback==="function"){this.callback(this.errors,e)}if(this.errors.length>0){if(e&&e.preventDefault){e.preventDefault()}else if(event){event.returnValue=false}}return true};g.prototype._validateField=function(e){var t=e.rules.split("|"),s=e.rules.indexOf("required"),r=!e.value||e.value===""||e.value===a;for(var l=0,u=t.length;l=parseInt(t,10)},max_length:function(e,t){if(!s.test(t)){return false}return e.value.length<=parseInt(t,10)},exact_length:function(e,t){if(!s.test(t)){return false}return e.value.length===parseInt(t,10)},greater_than:function(e,t){if(!l.test(e.value)){return false}return parseFloat(e.value)>parseFloat(t)},less_than:function(e,t){if(!l.test(e.value)){return false}return parseFloat(e.value)=0;s--){var r=n.charAt(s);a=parseInt(r,10);if(i){if((a*=2)>9)a-=9}t+=a;i=!i}return t%10===0},is_file_type:function(e,t){if(e.type!=="file"){return true}var a=e.value.substr(e.value.lastIndexOf(".")+1),i=t.split(","),n=false,s=0,r=i.length;for(s;s=parseInt(b,10):!1},max_length:function(a,b){return h.test(b)?a.value.length<=parseInt(b,10):!1},exact_length:function(a,b){return h.test(b)?a.value.length===parseInt(b,10):!1},greater_than:function(a,b){return k.test(a.value)?parseFloat(a.value)>parseFloat(b):!1},less_than:function(a,b){return k.test(a.value)?parseFloat(a.value) Date: Sun, 20 Sep 2015 20:39:00 -0700 Subject: [PATCH 38/40] Updates documentation for 2.0.0 --- index.html | 9 +++- validate.js | 108 +++++++++++++++++++++++++++++++++++++++++++----- validate.min.js | 32 +++++++------- 3 files changed, 123 insertions(+), 26 deletions(-) diff --git a/index.html b/index.html index 537efa9..3691bbe 100644 --- a/index.html +++ b/index.html @@ -152,10 +152,11 @@

    FormValidator

    new FormValidator(formName, fields, callback)
    • errors - An array of errors from the validation object. If the length > 0, the form failed validation

      -

      This array will contain javascript objects with up to three properties:
      +

      This array will contain javascript objects with up to four properties:
      - id: The id attribute of the form element
      - name: The name attribute of the form element
      - message: The error message to display
      + - messages: The error message of every failed validation of the given field to display
      - rule: The rule that prompted this error

    • event - If the browser supports it, the onsubmit event is passed in.
    • @@ -407,6 +408,12 @@

      Available Rules

      Release Notes

      +

      2.0.0 - 09/20/15

      + +
        +
      • Adds messages property to errors. It contains all of the failed validations.
      • +
      +

      1.4.1 - 08/20/14

        diff --git a/validate.js b/validate.js index 14c6f05..2e1e95e 100644 --- a/validate.js +++ b/validate.js @@ -1,6 +1,6 @@ /* - * validate.js 1.4.1 - * Copyright (c) 2011 - 2014 Rick Harrison, http://rickharrison.me + * validate.js 2.0.0 + * Copyright (c) 2011 - 2015 Rick Harrison, http://rickharrison.me * validate.js is open sourced under the MIT license. * Portions of validate.js are inspired by CodeIgniter. * http://rickharrison.github.com/validate.js @@ -36,7 +36,11 @@ valid_base64: 'The %s field must contain a base64 string.', valid_credit_card: 'The %s field must contain a valid credit card number.', is_file_type: 'The %s field must contain only %s files.', - valid_url: 'The %s field must contain a valid URL.' + valid_url: 'The %s field must contain a valid URL.', + greater_than_date: 'The %s field must contain a more recent date than %s.', + less_than_date: 'The %s field must contain an older date than %s.', + greater_than_or_equal_date: 'The %s field must contain a date that\'s at least as recent as %s.', + less_than_or_equal_date: 'The %s field must contain a date that\'s %s or older.' }, callback: function(errors) { @@ -60,7 +64,8 @@ ipRegex = /^((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){3}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})$/i, base64Regex = /[^a-zA-Z0-9\/\+=]/i, numericDashRegex = /^[\d\-\s]+$/, - urlRegex = /^((http|https):\/\/(\w+:{0,1}\w*@)?(\S+)|)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/; + urlRegex = /^((http|https):\/\/(\w+:{0,1}\w*@)?(\S+)|)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/, + dateRegex = /\d{4}-\d{1,2}-\d{1,2}/; /* * The exposed public object to validate a form: @@ -90,6 +95,9 @@ // If passed in incorrectly, we need to skip the field. if ((!field.name && !field.names) || !field.rules) { + console.warn('validate.js: The following field is being skipped due to a misconfiguration:'); + console.warn(field); + console.warn('Check to ensure you have properly configured a name and rules for this field'); continue; } @@ -340,20 +348,49 @@ } } - this.errors.push({ + var existingError; + for (var i = 0; i < this.errors.length; i += 1) { + if (field.id === this.errors[i].id) { + existingError = this.errors[i]; + } + } + var errorObject = existingError || { id: field.id, + display: field.display, element: field.element, name: field.name, message: message, + messages: [], rule: method - }); - - // Break out so as to not spam with validation errors (i.e. required and valid_email) - break; + }; + errorObject.messages.push(message); + if (!existingError) this.errors.push(errorObject); } } }; + /** + * private function _getValidDate: helper function to convert a string date to a Date object + * @param date (String) must be in format yyyy-mm-dd or use keyword: today + * @returns {Date} returns false if invalid + */ + FormValidator.prototype._getValidDate = function(date) { + if (!date.match('today') && !date.match(dateRegex)) { + return false; + } + + var validDate = new Date(), + validDateArray; + + if (!date.match('today')) { + validDateArray = date.split('-'); + validDate.setFullYear(validDateArray[0]); + validDate.setMonth(validDateArray[1] - 1); + validDate.setDate(validDateArray[2]); + } + return validDate; + }; + /* * @private * Object containing all of the validation hooks @@ -389,7 +426,7 @@ }, valid_emails: function(field) { - var result = field.value.split(","); + var result = field.value.split(/\s*,\s*/g); for (var i = 0, resultLength = result.length; i < resultLength; i++) { if (!emailRegex.test(result[i])) { @@ -523,9 +560,60 @@ } return inArray; + }, + + greater_than_date: function (field, date) { + var enteredDate = this._getValidDate(field.value), + validDate = this._getValidDate(date); + + if (!validDate || !enteredDate) { + return false; + } + + return enteredDate > validDate; + }, + + less_than_date: function (field, date) { + var enteredDate = this._getValidDate(field.value), + validDate = this._getValidDate(date); + + if (!validDate || !enteredDate) { + return false; + } + + return enteredDate < validDate; + }, + + greater_than_or_equal_date: function (field, date) { + var enteredDate = this._getValidDate(field.value), + validDate = this._getValidDate(date); + + if (!validDate || !enteredDate) { + return false; + } + + return enteredDate >= validDate; + }, + + less_than_or_equal_date: function (field, date) { + var enteredDate = this._getValidDate(field.value), + validDate = this._getValidDate(date); + + if (!validDate || !enteredDate) { + return false; + } + + return enteredDate <= validDate; } }; window.FormValidator = FormValidator; })(window, document); + +/* + * Export as a CommonJS module + */ +if (typeof module !== 'undefined' && module.exports) { + module.exports = FormValidator; +} diff --git a/validate.min.js b/validate.min.js index bd0d845..d0bad83 100644 --- a/validate.min.js +++ b/validate.min.js @@ -1,21 +1,23 @@ /* - * validate.js 1.4.1 - * Copyright (c) 2011 - 2014 Rick Harrison, http://rickharrison.me + * validate.js 2.0.0 + * Copyright (c) 2011 - 2015 Rick Harrison, http://rickharrison.me * validate.js is open sourced under the MIT license. * Portions of validate.js are inspired by CodeIgniter. * http://rickharrison.github.com/validate.js */ - -(function(q,r,m){var s={required:"The %s field is required.",matches:"The %s field does not match the %s field.","default":"The %s field is still set to default, please change.",valid_email:"The %s field must contain a valid email address.",valid_emails:"The %s field must contain all valid email addresses.",min_length:"The %s field must be at least %s characters in length.",max_length:"The %s field must not exceed %s characters in length.",exact_length:"The %s field must be exactly %s characters in length.", +(function(r,t,n){var u={required:"The %s field is required.",matches:"The %s field does not match the %s field.","default":"The %s field is still set to default, please change.",valid_email:"The %s field must contain a valid email address.",valid_emails:"The %s field must contain all valid email addresses.",min_length:"The %s field must be at least %s characters in length.",max_length:"The %s field must not exceed %s characters in length.",exact_length:"The %s field must be exactly %s characters in length.", greater_than:"The %s field must contain a number greater than %s.",less_than:"The %s field must contain a number less than %s.",alpha:"The %s field must only contain alphabetical characters.",alpha_numeric:"The %s field must only contain alpha-numeric characters.",alpha_dash:"The %s field must only contain alpha-numeric characters, underscores, and dashes.",numeric:"The %s field must contain only numbers.",integer:"The %s field must contain an integer.",decimal:"The %s field must contain a decimal number.", -is_natural:"The %s field must contain only positive numbers.",is_natural_no_zero:"The %s field must contain a number greater than zero.",valid_ip:"The %s field must contain a valid IP.",valid_base64:"The %s field must contain a base64 string.",valid_credit_card:"The %s field must contain a valid credit card number.",is_file_type:"The %s field must contain only %s files.",valid_url:"The %s field must contain a valid URL."},t=function(a){},u=/^(.+?)\[(.+)\]$/,h=/^[0-9]+$/,v=/^\-?[0-9]+$/,k=/^\-?[0-9]*\.?[0-9]+$/, -p=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,w=/^[a-z]+$/i,x=/^[a-z0-9]+$/i,y=/^[a-z0-9_\-]+$/i,z=/^[0-9]+$/i,A=/^[1-9][0-9]*$/i,B=/^((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){3}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})$/i,C=/[^a-zA-Z0-9\/\+=]/i,D=/^[\d\-\s]+$/,E=/^((http|https):\/\/(\w+:{0,1}\w*@)?(\S+)|)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/,f=function(a,b,c){this.callback=c||t;this.errors=[];this.fields= -{};this.form=this._formByNameOrNode(a)||{};this.messages={};this.handlers={};this.conditionals={};a=0;for(c=b.length;a=parseInt(b,10):!1},max_length:function(a,b){return h.test(b)?a.value.length<=parseInt(b,10):!1},exact_length:function(a,b){return h.test(b)?a.value.length===parseInt(b,10):!1},greater_than:function(a,b){return k.test(a.value)?parseFloat(a.value)>parseFloat(b):!1},less_than:function(a,b){return k.test(a.value)?parseFloat(a.value)=parseInt(b,10):!1},max_length:function(a,b){return k.test(b)?a.value.length<=parseInt(b,10):!1},exact_length:function(a,b){return k.test(b)?a.value.length===parseInt(b,10):!1},greater_than:function(a,b){return l.test(a.value)?parseFloat(a.value)>parseFloat(b): +!1},less_than:function(a,b){return l.test(a.value)?parseFloat(a.value)d:!1},less_than_date:function(a,b){var c=this._getValidDate(a.value),d=this._getValidDate(b);return d&&c?c=d:!1},less_than_or_equal_date:function(a,b){var c=this._getValidDate(a.value),d=this._getValidDate(b);return d&&c?c<=d:!1}};r.FormValidator=g})(window,document); +"undefined"!==typeof module&&module.exports&&(module.exports=FormValidator); From 3bee3e38c4c11ead523edb1302b541dee624b0db Mon Sep 17 00:00:00 2001 From: Rick Harrison Date: Tue, 19 Jan 2016 11:58:59 -0800 Subject: [PATCH 39/40] Updates built files for 2.0.1 --- validate.js | 17 +++++++++-------- validate.min.js | 30 +++++++++++++++--------------- 2 files changed, 24 insertions(+), 23 deletions(-) diff --git a/validate.js b/validate.js index 2e1e95e..357aadf 100644 --- a/validate.js +++ b/validate.js @@ -1,5 +1,5 @@ /* - * validate.js 2.0.0 + * validate.js 2.0.1 * Copyright (c) 2011 - 2015 Rick Harrison, http://rickharrison.me * validate.js is open sourced under the MIT license. * Portions of validate.js are inspired by CodeIgniter. @@ -276,7 +276,8 @@ */ FormValidator.prototype._validateField = function(field) { - var rules = field.rules.split('|'), + var i, j, + rules = field.rules.split('|'), indexOfRequired = field.rules.indexOf('required'), isEmpty = (!field.value || field.value === '' || field.value === undefined); @@ -284,7 +285,7 @@ * Run through the rules and execute the validation methods as needed */ - for (var i = 0, ruleLength = rules.length; i < ruleLength; i++) { + for (i = 0, ruleLength = rules.length; i < ruleLength; i++) { var method = rules[i], param = null, failed = false, @@ -349,11 +350,12 @@ } var existingError; - for (var i = 0; i < this.errors.length; i += 1) { - if (field.id === this.errors[i].id) { - existingError = this.errors[i]; + for (j = 0; j < this.errors.length; j += 1) { + if (field.id === this.errors[j].id) { + existingError = this.errors[j]; } } + var errorObject = existingError || { id: field.id, display: field.display, @@ -556,7 +558,7 @@ len = typeArray.length; for (i; i < len; i++) { - if (ext == typeArray[i]) inArray = true; + if (ext.toUpperCase() == typeArray[i].toUpperCase()) inArray = true; } return inArray; @@ -608,7 +610,6 @@ }; window.FormValidator = FormValidator; - })(window, document); /* diff --git a/validate.min.js b/validate.min.js index d0bad83..2207ad2 100644 --- a/validate.min.js +++ b/validate.min.js @@ -1,23 +1,23 @@ /* - * validate.js 2.0.0 + * validate.js 2.0.1 * Copyright (c) 2011 - 2015 Rick Harrison, http://rickharrison.me * validate.js is open sourced under the MIT license. * Portions of validate.js are inspired by CodeIgniter. * http://rickharrison.github.com/validate.js */ -(function(r,t,n){var u={required:"The %s field is required.",matches:"The %s field does not match the %s field.","default":"The %s field is still set to default, please change.",valid_email:"The %s field must contain a valid email address.",valid_emails:"The %s field must contain all valid email addresses.",min_length:"The %s field must be at least %s characters in length.",max_length:"The %s field must not exceed %s characters in length.",exact_length:"The %s field must be exactly %s characters in length.", +(function(r,t,l){var u={required:"The %s field is required.",matches:"The %s field does not match the %s field.","default":"The %s field is still set to default, please change.",valid_email:"The %s field must contain a valid email address.",valid_emails:"The %s field must contain all valid email addresses.",min_length:"The %s field must be at least %s characters in length.",max_length:"The %s field must not exceed %s characters in length.",exact_length:"The %s field must be exactly %s characters in length.", greater_than:"The %s field must contain a number greater than %s.",less_than:"The %s field must contain a number less than %s.",alpha:"The %s field must only contain alphabetical characters.",alpha_numeric:"The %s field must only contain alpha-numeric characters.",alpha_dash:"The %s field must only contain alpha-numeric characters, underscores, and dashes.",numeric:"The %s field must contain only numbers.",integer:"The %s field must contain an integer.",decimal:"The %s field must contain a decimal number.", is_natural:"The %s field must contain only positive numbers.",is_natural_no_zero:"The %s field must contain a number greater than zero.",valid_ip:"The %s field must contain a valid IP.",valid_base64:"The %s field must contain a base64 string.",valid_credit_card:"The %s field must contain a valid credit card number.",is_file_type:"The %s field must contain only %s files.",valid_url:"The %s field must contain a valid URL.",greater_than_date:"The %s field must contain a more recent date than %s.",less_than_date:"The %s field must contain an older date than %s.", -greater_than_or_equal_date:"The %s field must contain a date that's at least as recent as %s.",less_than_or_equal_date:"The %s field must contain a date that's %s or older."},v=function(a){},w=/^(.+?)\[(.+)\]$/,k=/^[0-9]+$/,x=/^\-?[0-9]+$/,l=/^\-?[0-9]*\.?[0-9]+$/,q=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,y=/^[a-z]+$/i,z=/^[a-z0-9]+$/i,A=/^[a-z0-9_\-]+$/i,B=/^[0-9]+$/i,C=/^[1-9][0-9]*$/i,D=/^((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){3}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})$/i, -E=/[^a-zA-Z0-9\/\+=]/i,F=/^[\d\-\s]+$/,G=/^((http|https):\/\/(\w+:{0,1}\w*@)?(\S+)|)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/,H=/\d{4}-\d{1,2}-\d{1,2}/,g=function(a,b,c){this.callback=c||v;this.errors=[];this.fields={};this.form=this._formByNameOrNode(a)||{};this.messages={};this.handlers={};this.conditionals={};a=0;for(c=b.length;a=parseInt(b,10):!1},max_length:function(a,b){return k.test(b)?a.value.length<=parseInt(b,10):!1},exact_length:function(a,b){return k.test(b)?a.value.length===parseInt(b,10):!1},greater_than:function(a,b){return l.test(a.value)?parseFloat(a.value)>parseFloat(b): -!1},less_than:function(a,b){return l.test(a.value)?parseFloat(a.value)d:!1},less_than_date:function(a,b){var c=this._getValidDate(a.value),d=this._getValidDate(b);return d&&c?c=d:!1},less_than_or_equal_date:function(a,b){var c=this._getValidDate(a.value),d=this._getValidDate(b);return d&&c?c<=d:!1}};r.FormValidator=g})(window,document); -"undefined"!==typeof module&&module.exports&&(module.exports=FormValidator); +greater_than_or_equal_date:"The %s field must contain a date that's at least as recent as %s.",less_than_or_equal_date:"The %s field must contain a date that's %s or older."},v=function(a){},w=/^(.+?)\[(.+)\]$/,g=/^[0-9]+$/,x=/^\-?[0-9]+$/,m=/^\-?[0-9]*\.?[0-9]+$/,q=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,y=/^[a-z]+$/i,z=/^[a-z0-9]+$/i,A=/^[a-z0-9_\-]+$/i,B=/^[0-9]+$/i,C=/^[1-9][0-9]*$/i,D=/^((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){3}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})$/i, +E=/[^a-zA-Z0-9\/\+=]/i,F=/^[\d\-\s]+$/,G=/^((http|https):\/\/(\w+:{0,1}\w*@)?(\S+)|)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/,H=/\d{4}-\d{1,2}-\d{1,2}/,f=function(a,c,b){this.callback=b||v;this.errors=[];this.fields={};this.form=this._formByNameOrNode(a)||{};this.messages={};this.handlers={};this.conditionals={};a=0;for(b=c.length;a=parseInt(c,10):!1},max_length:function(a,c){return g.test(c)?a.value.length<=parseInt(c,10):!1},exact_length:function(a,c){return g.test(c)?a.value.length===parseInt(c,10):!1},greater_than:function(a, +c){return m.test(a.value)?parseFloat(a.value)>parseFloat(c):!1},less_than:function(a,c){return m.test(a.value)?parseFloat(a.value)d:!1},less_than_date:function(a,c){var b=this._getValidDate(a.value),d=this._getValidDate(c);return d&&b?b=d:!1},less_than_or_equal_date:function(a,c){var b=this._getValidDate(a.value),d=this._getValidDate(c);return d&&b?b<=d:!1}};r.FormValidator= +f})(window,document);"undefined"!==typeof module&&module.exports&&(module.exports=FormValidator); From 652452219d3b9da8ecfc4d08163f1efd53506768 Mon Sep 17 00:00:00 2001 From: Luis Fernando Gomez Alejandre Date: Mon, 9 Jul 2018 22:04:52 -0500 Subject: [PATCH 40/40] Create traslation Spanish If you can use a spanish defaults, only remplace these lines --- traslation-spanish | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 traslation-spanish diff --git a/traslation-spanish b/traslation-spanish new file mode 100644 index 0000000..11c8ce6 --- /dev/null +++ b/traslation-spanish @@ -0,0 +1,30 @@ +var defaults = { + messages: { + required: 'El %s campo es requerido.', + matches: 'El %s campo no coincide con el %s campo.', + "default": 'El %s campo sigue por defecto, por favor cambielo.', + valid_email: 'El %s campo debe contener una dirreccion de correo valida.', + valid_emails: 'El %s campo debe contener todos los emails validos.', + min_length: 'El %s campo debe tener al menos %s caracteres.', + max_length: 'El %s no debe sobrepasar de %s caracteres.', + exact_length: 'El %s campo debe tener exactamente %s caracteres.', + greater_than: 'El %s campo debe tener un numero mayor a %s.', + less_than: 'El %s campo debe contener un numero menor a %s.', + alpha: 'El %s campo debe solo contener caracteres alfabeticos.', + alpha_numeric: 'El %s campo solo debe contener caracteres alfanumericos.', + alpha_dash: 'El %s campo must solo debe contener alfanumericos caracteres guiones y guiones bajos.', + numeric: 'El %s campo solo debe contener numeros enteros.', + integer: 'El %s campo debe contener numeros.', + decimal: 'El %s campo debe contener un numero decimal.', + is_natural: 'El %s campo debe contener solo numeros positivos.', + is_natural_no_zero: 'El %s campo debe contener numeros mayores que cero.', + valid_ip: 'El %s campo debe contener una dirección IP valida.', + valid_base64: 'El %s campo debe contener una cadena de texto en base64.', + valid_credit_card: 'El %s campo debe contener un numero de tarjeta de credito valida.', + is_file_type: 'El %s campo solo debe contener %s archivos.', + valid_url: 'El %s campo debe contener una URL valida.', + greater_than_date: 'El %s campo debe contener una fecha más reciente que %s.', + less_than_date: 'El %s campo debe contener una fecha más antigua que %s.', + greater_than_or_equal_date: 'El %s campo debe contener una fecha igual o más reciente que %s.', + less_than_or_equal_date: 'El %s campo debe contener una fecha igual o más antigua que %s.' + }