element ui 表单校验的多种姿势

<template>
  <div>
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item
        prop="userName"
        label="用户名"
      >
        <el-input v-model="form.userName"></el-input>
      </el-form-item>
      <!--标签内的验证-->
      <el-form-item label="用户名"  :prop="userName" :rules="[{ required: true, message: '请输入用户名',trigger: 'blur'}]">
         <el-input v-model="userName" :maxlength="16" placeholder clearable></el-input>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import API from '@/api/rules'
export default {
  components: {},
  name: 'rules',
  data() {
      // 后台校验
    let validateUserName = (rule, value, callback) => {
      // 调用后台API校验用户名是否已存在
      API.validateUserNameApi(value).then(res => {
        if (res) {
          callback(new Error('账号已存在!'))
        } else {
          callback()
        }
      }).catch(() => {
        callback(new Error('账号验证重复api出错!'))
      })
    }
    return {
      form: {
        userName: ''
      },
      rules: {
        userName: [
          // elementUI 常规校验
          { required: true, min: 3, max: 20, message: '账户为3~20位', trigger: ['blur', 'change'] },
          // 正则表达式校验
          { pattern: /^[A-Za-z0-9_]+$/, message: '由字母、数字、下划线组成', trigger: ['blur', 'change'] },
          // 后台校验
          { validator: validateUserName, trigger: 'blur' }
        ]
      }
    }
  }
}
</script>

你可能感兴趣的:(element,ui,vue,element,ui,表单校验,element,ui,表单API校验,vue+element,ui的校验,element,ui,表单正则校验,element,ui,表单校验的多种姿势)