element-ui表单验证(验证手机号是否正确,自定义验证规则)

效果图

1. html

<el-form :model="userForm"
             status-icon
             :rules="rules"
             class="login-form"
             ref="userForm">
      <el-form-item class="login-head"></el-form-item>
      <el-form-item prop="mobile">
        <el-input v-model="userForm.mobile"
                  placeholder="请输入手机号"></el-input>
      </el-form-item>
      <el-form-item prop="code">
        <el-input v-model="userForm.code"
                  placeholder="请输入验证码"></el-input>
      </el-form-item>
      <el-form-item prop="agree">
        <el-checkbox v-model="userForm.agree">我已阅读并同意用户协议</el-checkbox>
      </el-form-item>
      <el-form-item>
        <el-button type="primary"
                   class="login-btn"
                   :loading="loginLoading"
                   @click="onLogin">登录</el-button>
      </el-form-item>
    </el-form>

2. script

export default {
  name: 'login',
  data () {
    // 自定义表单验证是否勾选协议协议
    var validateAgree = (rule, value, callback) => {
      if (value) {
        callback()
      } else {
        callback(new Error('请勾选同意协议'))
      }
    }
    // rule:验证的详细信息
    // value:验证是否通过,false失败,true通过
    // callback:回调函数 
    return {
      userForm: {
        mobile: '13911111111',
        code: '246810',
        agree: false // 协议
      },
      checked: false, // 复选框
      loginLoading: false, // 按钮加载状态
      rules: {
        mobile: [
          // 添加正则表达式 pattern: /^1[3|5|7|8|9]\d{9}$/,验证手机号是否正确
          { required: true, message: '请输入手机号', trigger: 'change' },
          { pattern: /^1[3|5|7|8|9]\d{9}$/, message: '请输入正确的号码格式', trigger: 'change' }
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'change' }
        ],
        // 自定义验证是否勾选协议
        agree: [
          { validator: validateAgree, trigger: 'change' }
        ]
      }
    }
  },
  methods: {
    onLogin () {
      // validate是异步请求
      this.$refs.userForm.validate(valid => {
        // 如果验证失败,不发送请求
        if (!valid) {
          return false
        }
        this.login()
      })
    },
    login () {
      this.loginLoading = true
      login(this.userForm).then(res => {
        // console.log(res)
        this.$message.success('登录成功!')
        this.loginLoading = false
      }).catch(err => {
        this.$message.error('登录失败!', err)
        this.loginLoading = false
      })
    }
  }
}

你可能感兴趣的:(vue)