<template>
    <div class="ht-base-form-custom-validator-demo">
        <ht-base-form ref="formCustom" :model="formCustom" :rules="ruleCustom" :label-width="80">
            <ht-base-form-item label="密码" prop="passwd">
                <ht-base-input type="password" v-model="formCustom.passwd" placeholder="请输入密码"></ht-base-input>
            </ht-base-form-item>
            <ht-base-form-item label="确认" prop="passwdCheck">
                <ht-base-input type="password" v-model="formCustom.passwdCheck" placeholder="请二次确认密码"></ht-base-input>
            </ht-base-form-item>
            <ht-base-form-item>
                <ht-base-button type="primary" @click="handleSubmit('formCustom')">确定</ht-base-button>
                <ht-base-button @click="handleReset('formCustom')" style="margin-left: 8px">重置</ht-base-button>
            </ht-base-form-item>
        </ht-base-form>
    </div>
</template>

<script>
  export default {
      name: 'HtBaseFormCustomValidatorDemo',
      data () {
          const validatePass = (rule, value, callback) => {
              if (value === '') {
                  callback(new Error('请输入密码！'));
              } else {
                  if (this.formCustom.passwdCheck !== '') {
                      // 对第二个密码框单独验证
                      this.$refs.formCustom.validateField('passwdCheck');
                  }
                  callback();
              }
          };
          const validatePassCheck = (rule, value, callback) => {
              if (value === '') {
                  callback(new Error('请确认密码！'));
              } else if (value !== this.formCustom.passwd) {
                  callback(new Error('两次输入的密码不一致'));
              } else {
                  callback();
              }
          };

          return {
              formCustom: {
                  passwd: '',
                  passwdCheck: ''
              },
              ruleCustom: {
                  passwd: [
                      { validator: validatePass, trigger: 'blur' }
                  ],
                  passwdCheck: [
                      { validator: validatePassCheck, trigger: 'blur' }
                  ]
              }
          }
      },
      methods: {
          handleSubmit (name) {
              this.$refs[name].validate((valid) => {
                  if (valid) {
                      this.$HtBaseMessage.success('Success!');
                  } else {
                      this.$HtBaseMessage.error('Fail!');
                  }
              })
          },
          handleReset (name) {
              this.$refs[name].resetFields();
          }
      }
  }
</script>
<style>
    .ht-base-form-custom-validator-demo {
        width:500px;
        margin: 0 auto;
    }
</style>

