Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Added length validator.

  • Loading branch information...
commit 1d840357fbe441675ef0bb520be02a6cd6b3476a 1 parent f98d76f
@tuxychandru authored
Showing with 19 additions and 2 deletions.
  1. +15 −0 grasshopper/lib/model.js
  2. +4 −2 test/simple/model-test.js
View
15 grasshopper/lib/model.js
@@ -33,6 +33,7 @@ exports.api.initModel = function(modelCtor, props) {
modelCtor.prototype.isValid = isValid;
modelCtor.prototype.addError = addError;
modelCtor.prototype.validateRequired = validateRequired;
+ modelCtor.prototype.validateLength = validateLength;
modelCtor.prototype.validateNumeric = validateNumeric;
modelCtor.prototype.validateDate = validateDate;
modelCtor.prototype.validatePattern = validatePattern;
@@ -124,6 +125,20 @@ function validateRequired(propName, error, prefix) {
}
}
+function validateLength(propName, min, max, error, prefix) {
+ if(typeof error == 'boolean') {
+ prefix = error;
+ error = 'length';
+ } else {
+ error = error || 'length';
+ }
+
+ if(this[propName]() !== undefined && this[propName]() !== null
+ && (this[propName]().length < min || this[propName]().length > max)) {
+ this.addError(propName, error, prefix);
+ }
+}
+
function validateNumeric(propName, error, prefix) {
if(typeof error == 'boolean') {
prefix = error;
View
6 test/simple/model-test.js
@@ -7,11 +7,12 @@ exports.suite = suite;
function Person() {
}
-gh.initModel(Person, 'name', 'age', 'dob', 'someProp', 'friends');
+gh.initModel(Person, 'name', 'age', 'sex', 'dob', 'someProp', 'friends');
Person.prototype.validate = function(next) {
this.validateRequired('name', 'Name is required.', false);
this.validateNumeric('age', false);
+ this.validateLength('sex', 1, 1);
this.validateDate('dob');
this.validatePattern('someProp', /^\d.*/);
}
@@ -83,10 +84,11 @@ suite.tests = {
'Trigger validations.': function(next) {
var p = new Person();
- p.update({age: 'ABC', dob: 'XYZ'});
+ p.update({sex: 'Male', age: 'ABC', dob: 'XYZ'});
assert.ok(!p.isValid());
assert.equal(p.errors['name'][0], 'Name is required.');
assert.equal(p.errors['age'][0], 'numeric');
+ assert.equal(p.errors['sex'][0], 'Person.sex.length');
assert.equal(p.errors['dob'][0], 'Person.dob.date');
assert.equal(p.errors['someProp'][0], 'Person.someProp.pattern');
next();
Please sign in to comment.
Something went wrong with that request. Please try again.