瀏覽器端和服務端均可以使用的驗證器

最近基於本身的使用習慣和經驗,寫了個驗證器。能夠在瀏覽器端和 Node 環境下使用。vue

但這種驗證器已經有很是多輪子了。。。沒有特點是不行的。。。git

這個驗證器的特點:github

1.內置規則以及可擴展規則shell

2.可使用邏輯操做符npm

3.支持一組檢驗規則,哪裏錯誤就提示那裏瀏覽器

4.小巧而且可擴展,能夠用多種形式封裝。工具

5.單元測試 100% 覆蓋綠單元測試

我本身就封裝了個 forms-validator,原本還想用 vue 封裝個的工具的,但沒時間就暫時坑了測試

下面來簡單介紹下,不過只介紹了部分功能。所有功能介紹,請看文檔ui

問題

先考慮下下面的場景

1.咱們要判斷,一個小於20或者大於60同時還必須爲素數的數字

2.校驗郵箱地址

  • 當用戶什麼都沒填,就點擊提交時,提示他,‘郵箱必填’('Required...')
  • 當用戶填了些東西時,校驗他是不是合法郵箱,而且是 Gmail 或者 QQ 郵箱,若是不是,點擊提交時,提示‘郵箱格式有誤’('Not a valid Email')
  • 當用戶郵箱填對了,而且是 Gmail 或者 QQ 郵箱了,校驗他字符長度,不能超過32個字符。若是超過了,提示‘郵箱地址太長’('Email address too long')

開始

先安裝

npm i --save validator-core

而後

import Validator from 'validator-core'
const validator = new Validator()

內置規則以及可擴展規則

詳細內置規則列表,見文檔

  • 好比限定字串長度:
validator.test('1234', 'size:4') // => true
validator.test('12345', 'size:4') // => false
validator.test('1234', 'size:2-4') // => true
validator.test('1', 'size:2-4') // => false
validator.test(null, 'size:2-4') // => false
validator.test(123, 'size:2-4') // => false
  • 判斷數字大小
validator.test(200, 'lt:400') // => true
validator.test(400, 'lte:400') // => true
validator.test(401, 'gt:400') // => true
  • 可擴展

好比這裏我擴展了三條規則(合理擴展規則能夠減小項目代碼量)

使用validator.registerRules方法來進行擴展

  • 'password': 校驗密碼是非特殊字符,而且8到16位
  • 'is_prime': 判斷數字是否爲素數
  • 'contain': 判斷字串是否包含另外一個字串
const customRules = {
  'password': /^[^\s\u4E00-\u9FA5]{8,16}$/,
  'is_prime': function isPrimeNum (num, params) {
    if (params) console.log(params)
    if (typeof num !== 'number' || !Number.isInteger(num)) return false

    if (num === 2) {
      return true
    } else if (num % 2 === 0) {
      return false
    }

    const squareRoot = Math.sqrt(num)
    for (var i = 3; i <= squareRoot; i += 2) {
      if (num % i === 0) return false
    }

    return true
  },
  'contain': function (value, params) {
    if (!params) return false
    if (typeof value !== 'string') return false

    for (let i = 0; i < params.length; i++) {
      const item = params[i]
      if (value.indexOf(item) > -1) return true
    }
    return false
  }
}

validator.registerRules(customRules)

validator.test('abcd123', 'password') // => false
validator.test('abcd1234', 'password') // => true
validator.test(13, 'is_prime:just_test,hei')
// log: ['just_test', 'hei']
// => true
validator.test(24, 'is_prime') // => false

使用邏輯操做符

咱們仍是接上面的例子。可使用的邏輯操做符有 &&, || 還有括號()

操做符不只能夠對內置規則使用,還能夠對擴展的規則使用。還能夠在一組校驗規則時使用(合理運用會很是強大,下面例子會說到)。

好比說,

  • 咱們要判斷用戶輸入的郵箱(內置規則爲email),是合法的,並且只支持 Gmail 和 QQ 郵箱,其餘不支持
  • 咱們要判斷,一個小於20或者大於60同時還必須爲素數的數字
validator.test('hwenleung@gmail.com', 'email && contain:gmail.com, qq.com') // => true
validator.test('hwenleung@163.com', 'email && contain:gmail.com, qq.com') // => false
validator.test('hwenleung@qq.com', 'email && contain:gmail.com, qq.com') // => true

validator.test(13, 'lt:20 || gt: 60 && is_prime') // => true
validator.test(23, 'lt:20 || gt: 60 && is_prime') // => false
validator.test(797, 'lt:20 || gt: 60 && is_prime') // => true

// 用括號來改變執行優先級
validator.test(4, 'lt:20 || (gt: 60 && is_prime)') // => true
validator.test(64, 'lt:20 || (gt: 60 && is_prime)') // => false
validator.test(797, 'lt:20 || (gt: 60 && is_prime)') // => true
validator.test(13, '((lt:20 || gt: 60) && is_prime)') // => true
validator.test(23, '((lt:20 || gt: 60) && is_prime)') // => false

支持一組檢驗規則,哪裏錯誤就提示那裏

繼續接上面的例子。考慮如下情景:

咱們有一個輸入郵箱地址的輸入框。

  • 當用戶什麼都沒填,就點擊提交時,提示他,‘郵箱必填’('Required...')
  • 當用戶填了些東西時,校驗他是不是合法郵箱,而且是 Gmail 或者 QQ 郵箱,若是不是,提示‘郵箱格式有誤’('Not a valid Email')
  • 當用戶郵箱填對了,而且是 Gmail 或者 QQ 郵箱了,校驗他字符長度,不能超過32個字符。若是超過了,提示‘郵箱地址太長’('Email address too long')

另外我還要校驗一個價格,不管他有什麼錯我都提示,‘通用的錯誤提示’('Common Mes: Error occur')

那麼就能夠用下面的代碼來實現 (ruleSet)

注意,使用一組檢驗規則(ruleSet)時,要用validator.check而不是validator.test

test是對單個規則用的。

// ruleSet must be an Object Array
const ruleSet = [
  {
    name: 'Email', // rule should have a unique name
    // set of rules will be checked in order
    rules: ['required', 'email && contain:gmail.com, qq.com', 'size:32'],
    // tips are one-to-one of the rules, but you can set only one tip like 'Price'
    tips: ['Required...', 'Not a valid Email', 'Email address too long']
  },
  {
    name: 'Price',
    rules: ['required', 'lt:5000'],
    // 當錯誤消息只有一個時,會當成默認信息
    tips: ['Common Mes: Error occur']
  }
]

const validator = new Validator(ruleSet)
// or
// const validator = new Validator()
// validator.use(ruleSet)

console.log(validator.check('', 'Email'))
// => {isError: true, isPass: false, name: 'Email', tip: 'Required...'}
console.log(validator.check('some@some', 'Email'))
// => {isError: true, isPass: false, name: 'Email', tip: 'Not a valid Email'}
console.log(validator.check('Iamveryloooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo@gmail.com', 'Email'))
// => {isError: true, isPass: false, name: 'Email', tip: 'Email address too long'}
console.log(validator.check('hwenleung@gmail.com', 'Email'))
// => {isError: false, isPass: true, name: 'Email'}

最後

詳細的文檔及項目源碼,在這裏

若是有幫助的話,歡迎點個 star ~~

相關文章
相關標籤/搜索