vue使用iview Form元件驗證(適用於後臺管理系統)

廖廖依發表於2018-07-19

forgetPwd.vue頁面

  1. 在template中使用iview Form元件
<template>
    <Form ref="forgetPwdForm" :label-width="100" :model="forgetPwdForm" :rules="vailRules" @submit.native.prevent="submit">
        <FormItem prop="mobile">
            <Input v-model="forgetPwdForm.mobile" placeholder="請輸入手機號"></Input>
        </FormItem>
        <FormItem prop="password">
            <Input v-model="forgetPwdForm.password" placeholder="請輸入密碼"></Input>
        </FormItem>
        <FormItem prop="confirmPwd">
            <Input v-model="forgetPwdForm.confirmPwd" placeholder="請確認密碼"></Input>
        </FormItem>
        <Button type="primary" @click.native="submit">確認</Button>
    </Form>
</template>
複製程式碼
  1. 定義變數
import iviewRules from './../libs/iviewRules.js'
export default {
    data () {
        /* 兩個forgetPwdForm值對比的需要寫在該位置 否則會報錯 */
        const valiConfirmPwd = (rule, value, callback) => {
            if (value !== this.forgetPwdForm.password) {
                callback(new Error('兩次輸入的密碼不一致'));
            } else {
                callback();
            }
        }
        return {
            forgetPwdForm: {
                mobile: '',
                password: '',
                confirmPwd: ''
            },
            vailRules: [
                mobile: [
                    {required: true, message: '請輸入手機號碼', trigger: 'blur'},
                    {validator: iviewRules.isPhone, message: '請輸入正確的手機號碼', trigger: 'blur'}
                ],
                password: [
                    {required: true, message: '請輸入密碼', trigger: 'blur'},
                    {type: 'string', min: 6, message: '密碼至少為6位字元', trigger: 'blur'},
                    {type: 'string', min: 20, message: '密碼至多為20位字元', trigger: 'blur'},
                ],
                confirmPwd: [
                    {required: true, message: '請確認密碼', trigger: 'blur'},
                    {validator: valiConfirmPwd, message: '兩次輸入的密碼不一致', trigger: 'blur'}
                ]
            ]
        }
    },
    methods: {
        submit () {
            this.$refs.forgetPwdForm.validate((valid) => {
                /* valid的值為true/false 如果全部驗證了定義的規則 則valid為true 否則為false 使用此方法 無需二次驗證 方便快捷*/
                if (valid) {
                    /* 驗證之後需要做的事情 */
                }
            })
        }
    }
}
複製程式碼
  1. vailFormate.js頁面
function Rules () {}
Rules.prototype.isPhone = function (value) {
    let reg = /^1[3|4|5|7|8]\d{9}/
    return reg.test(value)
}
export default new Rules()
複製程式碼
  1. iviewRules.js頁面
import rules from './../libs/vailFormate.js'
let iviewRules = {}
iviewRules.isPhone = (rule, value, callback) => {
    if (rules.isPhone(value)) {
        callback()
    } else {
        callback(new Error('手機號格式不正確'));
    }
}
export default iviewRules
複製程式碼

相關文章