欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

使用JS手寫一個類似?Laravel?驗證器的表單驗證器

 更新時間:2023年06月28日 09:57:39   作者:church  
這篇文章主要為大家介紹了使用JS手寫一個類似?Laravel?驗證器的表單驗證器實現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪

介紹

Laravel 的表單驗證很方便,想在前端也用這樣的方式進行驗證。

git 地址,歡迎star

期待這個表單驗證庫有這樣的功能。

let validator = new Validation(this.registerForm, {
    telephone: "required|telephone",
    captcha: "required|length:5",
}, {
    telephone: {
        required: "手機號不能為空",
        telephone: "手機號格式不正確",
    },
    captcha: "驗證碼不正確"
})
try {
    validator.validate()
} catch(e) {
    uni.showToast({
        icon: 'error',
        title: e.message
    })
}

構(gòu)造函數(shù)的第三個參數(shù) messages 可以不要,默認(rèn)是英文提示。而且該參數(shù)支持不同粒度的錯誤信息,如果傳對象,則如果對應(yīng)的規(guī)則校驗不通過,就使用對應(yīng)的錯誤信息;如果傳字符串,則不論什么規(guī)則未通過,都使用該錯誤信息。

內(nèi)置一些規(guī)則,如果不夠用,還可以自己擴展。

根據(jù)以上的需求,就有了這個庫 @church1117/form-validation。

安裝

npm install @church1117/form-validation

使用

import Validation from "@church1117/form-validation"
let data = {
        name: "church",
        mobile: "18565919379",
        age: 19,
        gender: '2',
        password: "123456",
        captcha: "12345",
        idcard: '42052919910727452X',
        email: "xxx@qq.com",
        test: "ttt",
        birthday: '1993/11/17',
    }
let rules = {
        name: "required|between:6,255",
        mobile: "required|telephone",
        age: "numeric|between:8,60",
        gender: "numeric|range:" + gender.join(','),
        password: "required|min:6|password",
        captcha: "required|length:5",
        idcard: "required|idcard",
        email: "email",
        // test: "required|testRule"
        birthday: "datetime"
    }
let messages = {
        name: {
            required: "名字不能為空",
            between: "名稱長度必須在6~255之間",
        },
        mobile: "不正確的手機格式",
        age: {
            numeric: "年齡不是一個有效的數(shù)值",
            between: "年齡必須在18-60歲之間"
        },
        password: {
            required: "密碼不能為空",
            min: "密碼長度不能小于6位",
            regex: "密碼只能由數(shù)字、大小寫字母構(gòu)成",
        },
        captcha: "驗證碼不正確",
        idcard: {
            required: "身份證不能為空",
            idcard: "身份證格式不正確",
        },
        test: {
            required: "測試字段不能為空",
            testRule: "該字段的值必須為test"
        }
    }
let validation = new Validation(data, rules, messages);
  • messages 可以定義不同粒度的錯誤信息,如果是字符串,那么該字段的所有驗證規(guī)則都使用該錯誤信息。如果是對象,就只使用對應(yīng)規(guī)則的錯誤信息。

內(nèi)置規(guī)則

  • required
  • telephone
  • min
  • max
  • between
  • idcard
  • range
  • password
  • numeric
  • length
  • email
  • datetime

自定義規(guī)則

匿名函數(shù)參數(shù)(value, field, ...params)

  • value
  • field
  • ...params
Validation.register('testRule', function(value, field) {
    if (typeof value != 'undefined' && value != 'test') {
        throw new Error(`${field} must equal test`)
    }
});

測試

npm test

以上就是使用JS手寫一個類似 Laravel 驗證器的表單驗證器的詳細(xì)內(nèi)容,更多關(guān)于JS Laravel表單驗證器的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評論