1.0.2 • Published 6 years ago

values-validator v1.0.2

Weekly downloads
2
License
ISC
Repository
github
Last release
6 years ago

Values Validator

Usage

validateValue()

const fieldErrors = validateValue({
  value: '',
  rules: ['required|email|max:250'],
  name: 'email',
  // Optional
  messages: {
    required: 'Email is required',
    email: 'Email is not valid',
    max: 'Email is too large'
  }
});

validateFields()

const formErrors = validateFields({
  values: {
    firstName: 'John',
    email: 'john@example.com'
  },
  validationRules: {
    firstName: 'required|max:250',
    email: 'required|email|max:250'
  }
  // Optional
  messages: {
    firstName: {
      required: 'First Name is a required field',
      max: 'First Name is too large'
    },
    email: {
      required: 'Email is required',
      email: 'Email is invalid',
      max: 'Email is too large'
    }
  }
});

Pre-defined rules

RuleDefinition
requiredChecks if value has a truthy value
maxMax limit of characters
minMin limit of characted
alphaChecks if value has only letters
creditCardChecks if value is a valid credit card

Custom rules

You can also pass a function as a rule. If the function returns false, then we add an error to the field.

const myCustomRule = value => value === 'bar';
const rules = [myCustomRule];

const fieldErrors = validateValue({ value: 'bar', rules, name: 'myField' });

In this case errors will be an empty array, because myCustomRule is returning true.

@TODO:

  • Add more pre-defined rules
  • Allow to add custom message for custom rules