Skip to content
This repository

Added form highlighting and some refactoring to the validation functions. #18

Closed
wants to merge 1 commit into from

1 participant

Alan Hietala
Alan Hietala

I've added input field highlighting to the library.

the class that gets set on the inputs is configured through defaults.errorClass.

I have also refactored the validation function into smaller functions that handle one task only. This increases readability and decouples validation from getting error messages associated with a field.

Alan Hietala AlanHietala Added field highlighting to the library. you can configure what the e…
…rror class is using defaults.errorClass. The implementation preserves existing classes on the input elements
5d85889
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Showing 1 unique commit by 1 author.

Feb 13, 2012
Alan Hietala AlanHietala Added field highlighting to the library. you can configure what the e…
…rror class is using defaults.errorClass. The implementation preserves existing classes on the input elements
5d85889
This page is out of date. Refresh to see the latest.

Showing 1 changed file with 121 additions and 45 deletions. Show diff stats Hide diff stats

  1. +121 45 validate.js
166 validate.js
@@ -34,6 +34,7 @@
34 34 valid_ip: 'The %s field must contain a valid IP.',
35 35 valid_base64: 'The %s field must contain a base64 string.'
36 36 },
  37 + errorClass: 'error',
37 38 callback: function(errors) {
38 39
39 40 }
@@ -73,6 +74,7 @@
73 74 var FormValidator = function(formName, fields, callback) {
74 75 this.callback = callback || defaults.callback;
75 76 this.errors = [];
  77 + this.errorClass = defaults.errorClass;
76 78 this.fields = {};
77 79 this.form = document.forms[formName] || {};
78 80 this.messages = {};
@@ -146,7 +148,6 @@
146 148
147 149 FormValidator.prototype._validateForm = function(event) {
148 150 this.errors = [];
149   -
150 151 for (var key in this.fields) {
151 152 if (this.fields.hasOwnProperty(key)) {
152 153 var field = this.fields[key] || {},
@@ -161,7 +162,7 @@
161 162 /*
162 163 * Run through the rules for each field.
163 164 */
164   -
  165 + this._clearHightlightFromField(field);
165 166 this._validateField(field);
166 167 }
167 168 }
@@ -185,10 +186,12 @@
185 186 /*
186 187 * @private
187 188 * Looks at the fields value and evaluates it against the given rules
  189 + * @returns true if valid, false if invalid
188 190 */
189   -
190 191 FormValidator.prototype._validateField = function(field) {
191   - var rules = field.rules.split('|');
  192 + var rules = field.rules.split('|'),
  193 + ruleValid = false,
  194 + validatorMessage = null;
192 195
193 196 /*
194 197 * If the value is null and not required, we don't need to run through validation
@@ -203,62 +206,135 @@
203 206 */
204 207
205 208 for (var i = 0, ruleLength = rules.length; i < ruleLength; i++) {
206   - var method = rules[i],
207   - param = null,
208   - failed = false;
209   -
210   - /*
211   - * If the rule has a parameter (i.e. matches[param]) split it out
212   - */
  209 +
  210 + ruleValid = this._validateRule(field,rules[i]);
213 211
214   - if (parts = ruleRegex.exec(method)) {
215   - method = parts[1];
216   - param = parts[2];
  212 + if (!ruleValid) {
  213 +
  214 + validatorMessage = this._getValidatorMessage(field);
  215 + this.errors.push(validatorMessage);
  216 + this._highlightField(field);
  217 + // Break out so as to not spam with validation errors (i.e. required and valid_email)
  218 + break;
217 219 }
  220 + }
  221 + };
218 222
219   - /*
220   - * If the hook is defined, run it to find any validation errors
221   - */
  223 + /*
  224 + * @private
  225 + * Given a rule and a field validates it
  226 + * @returns true if valid and false if invalid
  227 + */
  228 + FormValidator.prototype._validateRule = function(field, rule) {
  229 + var method = rule,
  230 + param = null,
  231 + parts = null,
  232 + failed = false;
  233 +
  234 + /*
  235 + * If the rule has a parameter (i.e. matches[param]) split it out
  236 + */
  237 +
  238 + if (parts = ruleRegex.exec(method)) {
  239 + method = parts[1];
  240 + param = parts[2];
  241 + }
  242 +
  243 + /*
  244 + * If the hook is defined, run it to find any validation errors
  245 + */
222 246
223   - if (typeof this._hooks[method] === 'function') {
224   - if (!this._hooks[method].apply(this, [field, param])) {
  247 + if (typeof this._hooks[method] === 'function') {
  248 + if (!this._hooks[method].apply(this, [field, param])) {
  249 + failed = true;
  250 + }
  251 + } else if (method.substring(0, 9) === 'callback_') {
  252 + // Custom method. Execute the handler if it was registered
  253 + method = method.substring(9, method.length);
  254 +
  255 + if (typeof this.handlers[method] === 'function') {
  256 + if (this.handlers[method].apply(this, [field.value]) === false) {
225 257 failed = true;
226 258 }
227   - } else if (method.substring(0, 9) === 'callback_') {
228   - // Custom method. Execute the handler if it was registered
229   - method = method.substring(9, method.length);
230   -
231   - if (typeof this.handlers[method] === 'function') {
232   - if (this.handlers[method].apply(this, [field.value]) === false) {
233   - failed = true;
234   - }
235   - }
236 259 }
  260 + }
  261 + return !failed;
  262 + };
237 263
238   - /*
239   - * If the hook failed, add a message to the errors array
240   - */
  264 + /*
  265 + * @private
  266 + * returns the validator message for a given field
  267 + */
  268 + FormValidator.prototype._getValidatorMessage = function(field,rule) {
  269 + // Make sure we have a message for this rule
241 270
242   - if (failed) {
243   - // Make sure we have a message for this rule
244   - var source = this.messages[method] || defaults.messages[method];
245 271
246   - if (source) {
247   - var message = source.replace('%s', field.display);
  272 + var method = rule,
  273 + parts = null,
  274 + source = this.messages[method] || defaults.messages[method],
  275 + message = null;
  276 +
  277 + /*
  278 + * If the rule has a parameter (i.e. matches[param]) split it out
  279 + */
  280 + if (parts = ruleRegex.exec(method)) {
  281 + method = parts[1];
  282 + param = parts[2];
  283 + }
248 284
249   - if (param) {
250   - message = message.replace('%s', (this.fields[param]) ? this.fields[param].display : param);
251   - }
  285 + if (source) {
  286 + message = source.replace('%s', field.display);
252 287
253   - this.errors.push(message);
254   - } else {
255   - this.errors.push('An error has occurred with the ' + field.display + ' field.');
256   - }
  288 + if (param) {
  289 + message = message.replace('%s', (this.fields[param]) ? this.fields[param].display : param);
  290 + }
257 291
258   - // Break out so as to not spam with validation errors (i.e. required and valid_email)
259   - break;
  292 +
  293 + } else {
  294 + message = 'An error has occurred with the ' + field.display + ' field.';
  295 + }
  296 +
  297 + return message;
  298 + };
  299 +
  300 + /*
  301 + * @private
  302 + * highlight the passed in field with the error class
  303 + */
  304 + FormValidator.prototype._highlightField = function(field) {
  305 + var element = this.form[field.name],
  306 + elClasses = [];
  307 +
  308 + if(element.className.trim() !== '') {
  309 + elClasses = element.className.split(' ');
  310 + }
  311 +
  312 + elClasses.push(this.errorClass);
  313 + element.className = elClasses.join(' ');
  314 +
  315 + };
  316 +
  317 +
  318 + /*
  319 + * @private
  320 + * clears a highlight from a field
  321 + */
  322 + FormValidator.prototype._clearHightlightFromField = function(field) {
  323 + var element = this.form[field.name],
  324 + elClasses = [],
  325 + newClasses = [];
  326 +
  327 + if(element.className.trim() !== '') {
  328 + elClasses = element.className.split(' ');
  329 +
  330 + for(var i = 0 ; i < elClasses.length; i++) {
  331 + if(elClasses[i] !== this.errorClass) {
  332 + newClasses.push(elClasses[i]);
  333 + }
260 334 }
261 335 }
  336 +
  337 + element.className = newClasses.join(' ');
262 338 };
263 339
264 340 /*

Tip: You can add notes to lines in a file. Hover to the left of a line to make a note

Something went wrong with that request. Please try again.