Home

Awesome

Satpam


Satpam is a javascript simple and effective object validation library.

Build Status npm version

Installation

npm install satpam --save

Quick Usage

const satpam = require('satpam');

const rules = {
  name: ['required'],
  phone: ['required', 'numeric'],
  email: ['required', 'email']
  office: {
    secondaryEmail: ['email'],
  }
};

const input = {
  name: 'Sendy',
  title: 'Lord',
  phone: 'hi there123',
  email: 'test@example.com',
  office: {
    secondaryEmail: 'invalid email',
  }
};

const result = satpam.validate(rules, input);

if (result.success === true) {
  // valid
} else {
  // invalid
  result.messages.office.secondaryEmail.email === 'Secondary Email must be email.';
  result.messages.phone.number === 'Phone must be numeric.';
}

Isolated Satpam Instance

Satpam create method will return an isolated Satpam instance based on current state of satpam validation rules and messages. The instance won't be affected when you setting up a custom validation rules or messages.

const satpam = require('satpam');

const validatorOne = satpam.create();
const validatorTwo = satpam.create();

Front End Usage

For front end usage, you can use the dedicated front end lib.

import satpam from 'satpam/lib/frontend';

Additionally, it's better to create your own validator instance with only the needed rules. This will help reduce build size especially if your front end application is intended for end users.

import Validator from 'satpam/lib/frontend/validator';
import minLength from 'satpam/lib/validators/min-length';
import maxLength from 'satpam/lib/validators/max-length';

const customValidator = new Validator({
  validators: [minLength, maxLength]
});

const result = customValidator.validate(
  { token: ['minLength:11', 'maxLength:16'] },
  { token: '12345' }
);

Available Rules

Complete Examples

To see complete example usage, please see the unit tests

Custom Validation Rules

Add custom validation rule(s) globally. Note that everytime you add a custom validation rule it will affect every Satpam instance(s) that is created after the custom rules addition, but not the old instance(s).

const satpam = require('satpam');

// oldValidator will not have `must-be-ironman` rule, because it's created
// before we add the custom validation.
const oldValidator = satpam.create();

// The global satpam validator will has updated validation rules.
// After this statement, we can do satpam.validate({name: ['must-be-ironman']}, ...);
satpam.addCustomValidation('must-be-ironman', val => val === 'ironman');
satpam.setValidationMessage('must-be-ironman', 'Not ironman D:');

// With parameters
satpam.addCustomValidation('range:$1:$2', (val, ruleObj) => {
  return val >= ruleObj.params[0] && val <= ruleObj.params[1];
});

// If validation fails it will set message to:
// "PropertyName must between 0 and 30"
satpam.setValidationMessage('range:$1:$2', '<%= propertyName %> must between <%= ruleParams[0] %> and <%= ruleParams[1] %>');

// newValidator will have `must-be-ironman` rule because it's created
// after we add the custom validation.
const newValidator = satpam.create();

Optional Validation

Sometimes you want the validation to pass if any of the validation rule is satisfied, we can do this by supplying the validation rules in an array.

const rules = {
  // It will pass if document is passed and either a pdf or an image
  document: ['required', ['fileType:pdf', 'image']]
};

Running Validation Based On Some Conditions

There's also a case when you only want to run a validation rule only if a specific condition is fulfilled.

const shouldValidateZipCode = (ruleObj, inputObj) => {
  return inputObj.livesInJakarta;
};

const rules = {
  // Only require zip code if `livesInJakarta` is truthy
  zipCode: [
    {name: 'required', shouldValidate: shouldValidateZipCode}
  ]
};

satpam.validate(rules, {}); // {success: true}
satpam.validate(rules, {
  livesInJakarta: true
}); // Will fail

Custom Validation Messages

You can override each validation rule's message

satpam.setValidationMessage(
  'minLength:$1',
  '<%= propertyName %> must have length more than <%= ruleParams[0] %>'
);

You can also pass a Function instead of a String

/**
 * @example
 * const satpam = require('satpam');
 *
 * const rules = {name: ['minLength:10']};
 * const input = {name: 'wubwub'};
 * satpam.validate(rules, input);
 *
 * expect(ruleObj.name).to.equal('minLength');
 * expect(ruleObj.fullName).to.equal('minLength:$1');
 * expect(ruleObj.params).to.deep.equal([10]);
 * expect(propertyName).to.equal('name');
 * expect(value).to.equal('wubwub');
 *
 * @param {Object} ruleObj
 * @param {String} ruleObj.name - The validation rule name
 *   e.g. `minLength:10` will have name minLength
 * @param {String} ruleObj.fullName - Validation rule fullname
 *   e.g. `minLength:10` will have fullName `minLength:$1`
 * @param {Array} ruleObj.params - The rule parameters
 *   e.g. `minlength:10` will have params `[10]`
 * @param {String} propertyName
 * @param {*} value
 */
const message = (ruleObj, propertyName, value) => {
  ...
};
satpam.setValidationMessage('minLength:$1', message);

License

MIT

Hi-Five