Import quival from jsdelivr CDN

by Mohd Hafizuddin M Marzuki

HTML

<pre id="output"></pre>

JavaScript

import { Validator } from 'https://cdn.jsdelivr.net/npm/[email protected]/src/index.js';
import enLocale from 'https://cdn.jsdelivr.net/npm/[email protected]/src/locales/en.js';

// Set localization messages
Validator.setLocale('en');
Validator.setMessages('en', enLocale);

// Register custom checker
Validator.addChecker(
  'phone_number',
  (attribute, value, parameters) => !/[^0-9\+\-\s]/.test(value),
  'The :attribute field must be a valid phone number.'
);

// Prepare arguments
const data = {
  refcode: '1bc',
  username: 'ideađź’ˇ',
  name: '',
  email: 'test',
  phone_number: 'test',
  letters: ['a', 'b', 'B', 'a'],
  items: {
    x: 'a',
    y: null,
    z: 12,
  },
  payment_type: 'cc',
  card_number: '',
};

const rules = {
  refcode: [
    'required',
    function (attribute, value) { // Closure rule
      return {
        success: /^[a-z]/i.test(value),
        message: 'The :attribute field must start with a letter.',
      };
    },
  ],
  username: ['required', 'ascii', 'min:3'],
  name: ['required', 'min:3'],
  email: ['required', 'email'],
  phone_number: ['required', 'phone_number', 'min:7'],
  'letters.*': ['distinct:ignore_case'],
  items: ['array', 'size:5'],
  'items.*': ['required', 'string'],
  payment_type: ['required', 'in:cc,paypal'],
  cc_number: ['required_if:payment_type,cc'],
};

const customMessages = {
  'items.size': 'The size of the array must be equal to :size items only.',
};

const customAttributes = {
  cc_number: 'Credit Card Number',
};

const customValues = {
  payment_type: {
    cc: 'credit card',
  },
};

// Create Validator instance
const validator = new Validator(data, rules, customMessages, customAttributes, customValues);

// Perform validation
const output = document.getElementById('output');

validator
  .validate()
  .then((errorBag) => {
		output.innerHTML = JSON.stringify(errorBag.messages(), null, 2);
  });