22

Form-validation.js – JavaScript form validation library

 3 years ago
source link: https://github.com/iendeavor/form-validation.js
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

form-validation.js

ToC

Status: Beta

Live Examples

vue@2 + element-ui

Feature

Intuitive APIs. :dart:

Asynchronous Rules Support.

Nested Object/Aray Support.

Array Manipulations (push, pop, shift, unshift, splice, reverse) Support.

Zero Dependencies, Native Javascript only.

Overview

const form = {
  account: '',
}

const schema = {
  account: {
    $params: {
      languageCode: 'en',
      minLength: 6,
    },

    $normalizer({ value, key, parent, path, root, params }) {
      return typeof value === 'string' ? value.trim() : ''
    },

    $rules: {
      weak({ value, key, parent, path, root, params }) {
        if (value.length < params.minLength) return 'Too short'
        if (/\W/.test(value)) return 'Must contain special charachar'
      },

      async alreadyBeenUsed({ value, key, parent, path, root, params }) {
        if (value === '') return

        if (await isExists(value)) return false
      },
    },

    $errors: {
      weak({ value, key, parent, path, root, params }) {
        return params.$rules.weak
      },

      alreadyBeenUsed({ value, key, parent, path, root, params }) {
        const languageCode = params.languageCode || 'en-US'
        return translate(`This account has already been used.`, { languageCode })
      },
    },
  },
}

const valdiator = {}

// in order to track form's data sctructure (e.g., add new property to object, or push new element to array), you should always update your fields from the proxiedForm instead of the original form
const proxiedForm = FormValidation.proxy({ form, schema, validator })

// validate the entire form
await valdiator.$v.validate()

console.log(valdiator.$v.invalid)
// > true
console.log(valdiator.$v.errors.weak)
// > 'Too short.'

Docs

Need help?

Please open GitHub issues . Please search previous issues before creating a new issue.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK