element-ui form单独验证某个el-form-item/获取验证码倒计时

单独验证某个表单
this.$refs.changeForm.validateField('newPhone')
changeForm:el-form的ref
newPhone:在data里定义的el-form的rules里对应的你需要验证的某个规则名称

在获取验证码的时候需要先判断手机号是否填写,提交的时候是整个表单验证,点击获取验证码的时候只验证手机号


image.png

          
确定
js: import { regEx } from '@/utils/regEx' import { phonecode, CheckCode } from '@/api/account/account' import { getCode } from '@/mixins/getCode' const validateTel = (rule, value, callback) => { if (value === '') { callback(new Error('请输入手机号码')) } else if (!regEx.mobile.test(value)) { callback(new Error('手机号码格式不正确')) } else { callback() } } export default { name: 'ChangePhone', mixins: [getCode], data () { return { pageType: 'changePhone', telphone: '12131312312', form: { code: '' }, changeForm: { newPhone: '', newCode: '' }, changeRules: { newPhone: { required: true, validator: validateTel, trigger: 'blur' }, newCode: { required: true, message: '请输入验证码', trigger: 'blur' } } } }, methods: { async restart () { try { if (this.codeCountdown <= 0) { const res = await phonecode(this.telphone) if (res.code === 200) { this.getCode() } } } catch (e) { console.log(e) } }, async changeRestart () { try { if (this.codeCountdown <= 0) { if (!this.changeForm.newPhone) { this.$refs.changeForm.validateField('newPhone') return false } const res = await phonecode(this.changeForm.newPhone) if (res.code === 200) { this.getCode() } } } catch (e) { console.log(e) } }, submitChange (formName) { try { this.$refs[formName].validate(async (valid) => { if (valid) { const res = await CheckCode(this.changeForm.newPhone, this.changeForm.newCode) if (res.code === 1 && res.msg === 'ok') { this.pageType = 'getCode' this.$message.success('手机修改成功') this.$emit('update:changePhone', false) } } else { console.log('error submit!!') return false } }) } catch (e) { console.log(e) } } }

验证码倒计时,如果多处用到,写成mixins
在src下新建mixins文件,在mixins下新建getCode.js文件

// getCode.js
export const getCode = {
  data () {
    return {
      codeCountdown: 0,
      timer: null
    }
  },
  computed: {
    codeBtnText () {
      return this.codeCountdown > 0
        ? `${this.codeCountdown}S后获取` : '获取验证码'
    }
  },
  methods: {
    async getCode () {
      if (this.codeCountdown > 0) {
        return
      }
      this.codeCountdown = 60
      this.timer = setInterval(() => {
        this.codeCountdown = Math.max(0, this.codeCountdown - 1)
        if (this.codeCountdown <= 0) {
          clearInterval(this.timer)
        }
      }, 1000)
    }
  }
}

在utils里新建regEx.js,专门用来放正则

// regEx.js
export const regEx = {
  specialPlaneL: /0\d{2,3}-\d{7,8}/, // 座机
  mobile: /^((0\d{2,3}-\d{7,8})|(1[3456789]\d{9}))$/, // 手机
  qq: /^[1-9][0-9]{4,14}$/, // qq
  email: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
  password: /(?!^(\d+|[a-zA-Z]+|[~!@#$%^&*?]+)$)^[\w~!@#$%^&*?]{8,18}$/
}

你可能感兴趣的:(element-ui form单独验证某个el-form-item/获取验证码倒计时)