ant design of vue 学习之用户信息表单验证

<template>
  <a-modal :title="editId ? '修改教师' : '添加教师'"
           v-model="show"
           :centered="true"
           :maskClosable="false"
           width="50%"
           @cancel="handleCancel"
           @ok="handleConfirm">
    <a-form :form="form">
      <a-form-item label="姓名"
                   v-bind="formItemLayout">
        <a-input placeholder="姓名"
                 v-decorator="['name', { rules: [{ required: true, max: 50, message: '必填项,最大50字符' }] }]" />
      a-form-item>
      <a-form-item label="性别"
                   v-bind="formItemLayout">
        <a-radio-group name="radioGroup"
                       v-decorator="['sex',{rules: [{ required: true,message:'请选择用户性别'}],initialValue:1}]">
          <a-radio :value="1">a-radio>
          <a-radio :value="0">a-radio>
        a-radio-group>
      a-form-item>
      <a-form-item label="文化程度"
                   v-bind="formItemLayout">
        <a-select placeholder="请选择文化程度"
                  v-decorator="['degreeOfEducation',{rules: [{ required: false, message: '请选择文化程度'}],initialValue:6}]">
                  <a-select-option v-for="item in educationList"
                           :key="item.value"
                           :value="item.value">
            {
    { item.key }}
          a-select-option>
        a-select>
      a-form-item>
      <a-form-item label="出生日期"
                 v-bind="formItemLayout">
      <a-date-picker :disabledDate="disabledDate"
                     v-decorator="['birthday', {rules: [{ type: 'object', required: true, message: '请选择出生日期' }]}]"
                     show-time  
                     format="YYYY-MM-DD HH:mm:ss" />
      a-form-item> 
       <a-form-item v-bind="formItemLayout"
                   label="手机号码">
        <a-input placeholder="手机号码"
                 v-decorator="['mobileNumber',{rules: [{ required: true,max:11,message:'请输入正确格式的手机号码',validator:MobileNumberValidator}]}]" />
      a-form-item>
            <a-form-item v-bind="formItemLayout"
                   label="邮箱">
        <a-input placeholder="请输入邮箱"
                 v-decorator="['email',{rules: [{ required: true,max:20,message:'请输入正确格式的邮箱!',validator:EmailValidator}]}]" />
      a-form-item>    
         <a-form-item v-bind="formItemLayout"
                   label="身份证号码">
        <a-input placeholder="请输入身份证号码"
                 v-decorator="['pid',{rules: [{ required: true,max:20,message:'请输入正确格式的身份证号码!',validator:IDValidator}]}]" />
      a-form-item>    
      <a-form-item label="研究方向"
                   v-bind="formItemLayout">
        <a-textarea placeholder="研究方向"
                    :autosize="{minRows:6,maxRows:10}"
                    v-decorator="['researchFields',{rules:[{required:false,message:'请输入研究方向(最大1000字符)',max:1000}]}]" />
      a-form-item>
      <a-form-item label="教研成果"
                   v-bind="formItemLayout">
        <a-textarea placeholder="教研成果"
             :autosize="{minRows:6,maxRows:10}"
                    v-decorator="['achievements',{rules:[{required:false,message:'请输入教研成果(最大1000字符)',max:1000}]}]" />
      a-form-item>
    a-form>
  a-modal>
template>     
        
      
          
<script>
import moment from 'moment'
import {
      addTeacher, updateTeacher } from '@/api/learning/teacher'
export default {
     
  props: ['visible', 'editId'],
  data () {
     
  return {
     
      form: this.$form.createForm(this),
      formItemLayout: {
     
        labelCol: {
     
          xs: {
      span: 24 },
          sm: {
      span: 8 }
        },
        wrapperCol: {
     
          xs: {
      span: 24 },
          sm: {
      span: 12 }
        }
      },
      unitSn: '',
      educationList: [
        {
     
          key: '无',
          value: 1
        },
        {
     
          key: '小学',
          value: 2
        }]
     }
  },
  computed: {
     
    show: {
     
      get: function () {
     
        return this.visible
      },
      set: function () {
      }
    }
  },
  methods: {
     
    // 应在当日之前,当日之后的不允许选择
    disabledDate (current) {
     
      return current && current > moment().endOf('day')
    },
    // 手机号验证
    MobileNumberValidator (rule, value, callback) {
     
      const idcardReg = /^1(3|4|5|6|7|8|9)\d{9}$/
      if (!idcardReg.test(value)) {
     
        // eslint-disable-next-line standard/no-callback-literal
        callback('非法格式')
      }
      // Note: 必须总是返回一个 callback,否则 validateFieldsAndScroll 无法响应
      callback()
    },
    // 邮箱验证
    EmailValidator (rule, value, callback) {
     
      const idcardReg = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/
      if (!idcardReg.test(value)) {
     
        // eslint-disable-next-line standard/no-callback-literal
        callback('非法格式')
      }
     // Note: 必须总是返回一个 callback,否则 validateFieldsAndScroll 无法响应
      callback()
    },
    // 身份证验证 
    IDValidator (rule, value, callback) {
     
      const idcardReg = /^[1-9][0-9]{5}(19|20)[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|31)|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}([0-9]|x|X)$/
      if (!idcardReg.test(value)) {
     
      // eslint-disable-next-line standard/no-callback-literal
        callback('非法格式')
      }
      // Note: 必须总是返回一个 callback,否则 validateFieldsAndScroll 无法响应
      callback()
    },
    setFormValues (record) {
     
      console.log('设置表单数据', record)
      const {
      birthday } = record
      record['birthday'] = moment(birthday)
       const fields = ['name', 'sex', 'degreeOfEducation', 'birthday', 'mobileNumber', 'email', 'pid', 'researchFields', 'achievements']
      Object.keys(record).forEach((key) => {
     
        if (fields.indexOf(key) !== -1) {
     
        this.form.getFieldDecorator(key)
          const obj = {
     }
          obj[key] = record[key]
          this.form.setFieldsValue(obj)
        }
      })
    },
     handleCancel () {
     
      this.form.resetFields()
      this.$emit('close')
    },   
     handleConfirm () {
     
      this.form.validateFields(async (err, values) => {
     
        if (!err) {
     
          const editId = this.editId
          values.birthday = values.birthday ? values.birthday.format('YYYY-MM-DD HH:mm:ss') : ''
          values.unitSn = this.unitSn || this.$store.getters.userInfo.unitSn
          console.log('保存values', values)
          if (editId) {
     
            values.id = editId
            updateTeacher(values).then(res => {
     
              if (res.code == 0) {
     
              this.$message.success('保存成功')
                this.handleCancel()
                this.$emit('confirm')
              } else {
     
                this.$message.error(res.message)
              }
            })
            } else {
     
            addTeacher(values).then(res => {
     
              if (res.code == 0) {
     
                this.$message.success('保存成功')
                this.handleCancel()
                this.$emit('confirm')
              } else {
     
                this.$message.error(res.message)
              }
            })
           }
        }
      })
    }
  }
}
</script> 
              

你可能感兴趣的:(Ant,Design,Vue)