Skip to content

ember-cli package, which adds validation support to your Ember-Data models.

License

Notifications You must be signed in to change notification settings

davidstevens37/ember-model-validator

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Ember-model-validator

Build Status npm version Ember Observer Score

ember-cli package, which adds validation support to your Ember-Data models.

This README outlines the details of collaborating on this Ember addon.

Purpose

This Ember cli addons borns from the necessity of having some sort of similar validation support like we have on Rails with Active Record Validations.

Installation

Install Ember-model-validator is easy as:

npm install ember-model-validator --save-dev

Validators

Common options

All validators accept the following options

  • message option. Overwrites the default message.
  • errorAs option. Sets the key name to be used when adding errors (default to property name).

Presence

A value is not present if it is empty or a whitespace string. It uses Ember.isBlank method.

  validations: {
    name: {
      presence: true
    }
  }

Acceptance

These values: ['1', 1, true] are the acceptable values. But you can specify yours with the accept option.

  validations: {
    acceptConditions: {
      acceptance: {accept: 'yes'}
    }
  }

The accept option receives either a string or an array of acceptable values.

Absence

Validates that the specified attributes are absent. It uses Ember.isPresent method.

  validations: {
    login: {
      absence: true
    }
  }

Format

Speficy a Regexp to validate with. It uses the match() method from String.

  validations: {
    legacyCode:{
      format: { with: /^[a-zA-Z]+$/ }
    }
  }

Length

Speficy the lengths that are allowed.

Options
  • A number. The exact length of the value allowed (Alias for is).
  • An array. Will expand to minimum and maximum. First element is the lower bound, second element is the upper bound.
  • is option. The exact length of the value allowed.
  • minimum option. The minimum length of the value allowed.
  • maximum option. The maximum length of the value allowed.
  validations: {
    socialSecurity: {
      length: 5
    },
    nsaNumber: {
      length: [3, 5]
    },
    chuncaluchoNumber: {
      length: { is: 10, message: 'this is not the length of a chuncalucho' }
    },
    hugeName:{
      length: {
        minimum: 3,
        maximum: 5
      }
    }
  }

Email

Validates the proper fortmat of the email.

  validations: {
    email: {
      email: true
    }
  }

ZipCode

The value must be a correct zipcode. Regexp used /^\b\d{5}(-\d{4})?\b$/i.

  validations: {
    postalCode:{
      zipCode: true
    }
  }

Hex Color

The value must be a correct Hexadecimal color.

  validations: {
    favoritColor:{
      color: true
    }
  }

Subdomain

The value must a well formatted subdomain. Here you can also specify reserved words.

  validations: {
    mySubdomain:{
      subdomain:{ reserved:['admin','blog'] }
    }
  }

URL

The value must a well formatted URL.

  validations: {
    myBlog: {
      URL: true
    }
  }

Inclusion

The value has to be included in a given set.

  validations: {
    name:{
      inclusion: { in: ['Jose Rene', 'Aristi Gol', 'Armani'] }
    }
  }

Exclusion

The value can't be included in a given set.

  validations: {
    name:{
      exclusion: { in: ['Gionvany Hernandez', 'Wilder Medina'] }
    }
  }

Numericality

The value has to have only numeric values.

  validations: {
    lotteryNumber:{
      numericality: true
    }
  }

CustomValidation

Define a custom callback funciton to validate the model's value. The validation callback is passed 3 values: the key, value, model's scope. return true (or a truthy value) to pass the validation, return false (or falsy value) to fail the validation.

  validations: {
    lotteryNumber: {
      custom: funciton(key, value, model){
        return model.get('accountBalance') > 1 ? true : false;
      }
    }
  }

this has the same action as above except will use a custom message insetad of the default.

  validations: {
    lotteryNumber: {
      custom: {
        validation: funciton(key, value, model){
          return model.get('accountBalance') > 1 ? true : false;
        },
        message: 'You can't win off of good looks and charm.'
      }
    }
  }

Password

A set of validators which are especially useful for validating passwords. Be aware that these all of these password-aimed validations will work standalone and carry the same common options with the rest of the validations. They don't only work for passwords!

  • mustContainCapital (capital case character).
  • mustContainLower (lower case character).
  • mustContainNumber
  • mustContainSpecial
  • length (explained in-depth above).
validations: {
  password: {
    presence: true,
    mustContainCapital: true,
    mustContainLower: true,
    mustContainNumber: true,
    mustContainSpecial: {
      message: 'One of these chacters is required: %@',
      acceptableChars: '-+_!@#$%^&*.,?()'
    },
    length: {
      minimum: 6
    }
  },
  someOtherThing: {
    mustContainSpecial: true
  }
}

Relations

This validator will run the validate() function for the specific relation. If it's a DS.hasMany relation then it will loop through all objects.

Note: The relations have to be embedded or the promise has to be already resolved.

  validations: {
    myHasManyRelation:{
      relations: ['hasMany']
    },
    myBelongsToRelation:{
      relations: ['belongsTo']
    }
  }

Usage

Ember-model-validator provides a mixin to be included in your models for adding validation support. This mixin can be imported from your app's namespace (e.g. ../mixins/model-validator in your models).

By including Ember-model-validator's mixin into your model, this will have a validate function available, it is a synchronous function which returns either true or false. You can also pass an option hash for excluding or forcing certain attributes to be validated.

//Using `except`
myModel.validate({except:['name', 'cellphone']});

//Using `only`
myModel.validate({only:['favoritColor', 'mainstreamCode']});

Usage Example

import DS from 'ember-data';
import Validator from '../mixins/model-validator';

export default DS.Model.extend(Validator,{
  name: DS.attr('string'),
  login: DS.attr('string'),
  secondName: DS.attr('string'),
  email: DS.attr('string'),
  bussinessEmail: DS.attr('string'),
  favoritColor: DS.attr('string'),
  legacyCode: DS.attr('string'),
  mainstreamCode: DS.attr('string'),
  lotteryNumber: DS.attr('number'),
  alibabaNumber: DS.attr('number'),
  acceptConditions: DS.attr('boolean'),

  postalCode:  DS.attr('string'),

  mySubdomain: DS.attr('string'),

  myBlog: DS.attr('string'),

  otherFakes: DS.hasMany('other-model'),

  otherFake: DS.belongsTo('other-model'),

  validations: {
    name: {
      presence: { errorAs:'profile.name' },
      inclusion: { in: ['Jose Rene', 'Aristi Gol', 'Armani'], message: 'Solo verde a morir' }
    },
    login: {
      absence: true
    },
    secondName: {
      exclusion: { in: ['Gionvany Hernandez', 'Wilder Medina'], message: 'Que iNrresponsabilidad' }
    },
    bussinessEmail: {
      presence: { message: 'sup dude, where\'s da email' },
      email: { message: 'Be professional ma men' }
    },
    favoritColor:{
      color: { message: 'not a hex color' }
    },
    email: {
      presence: true,
      email: true
    },
    mySubdomain:{
      subdomain:{ reserved:['admin','blog'], message: 'this subdomain is super invalid' }
    },
    myBlog: {
      URL: true
    },
    mainstreamCode: {
      format: { with: /^[a-zA-Z]+$/, message: 'nu nu, that\'s not the format' }
    },
    legacyCode:{
      format: { with: /^[a-zA-Z]+$/ }
    },
    alibabaNumber: {
      numericality: { message: 'is not abracadabra' }
    },
    lotteryNumber: {
      numericality: true
    },
    acceptConditions: {
      acceptance: true
    },
    postalCode:{
      zipCode: true
    },
    otherFakes:{
      relations: ['hasMany']
    },
    otherFake:{
      relations: ['belongsTo']
    }
  }

});

After setting the validationces on your model you will be able to:

import Ember from 'ember';

export default Ember.Route.extend(
  {
    actions: {
      saveFakeModel: function() {
        var _this = this,
            fakeModel = this.get('model');

        if(fakeModel.validate()){
          fakeModel.save().then(
            // Success
            function() {
              // Alert success
              console.log('ooooh yeah we just saved the FakeModel...');
            },

            // Error handling
            function(error) {
              // Alert failure
              console.log('There was a problem saving the FakeModel...');
              console.log(error);
            }
          );
        }else{
          fakeModel.get('errors');
        }
      },
    }
  }
);

Running Tests

  • ember test
  • ember test --server

Building

  • ember build

For more information on using ember-cli, visit http://www.ember-cli.com/.

About

ember-cli package, which adds validation support to your Ember-Data models.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • JavaScript 95.9%
  • HTML 4.0%
  • Handlebars 0.1%