---
# System prepended metadata

title: Vuelidate 教學 (適用於前台/後台)

---

Vuelidate 教學 (適用於前台/後台)

[參考] https://vuelidate-next.netlify.app/


- 步驟一

**安裝套件vulidate**
```
"@vuelidate/core": "^2.0.0",
"@vuelidate/validators": "^2.0.0",
```

- 步驟二

 **新增一個Error組件**
 
>  說明:  裡面有2個props 一個前端的驗證資料,  一個是後端給的驗證錯誤訊息,  因為有可能有前端無法知道的驗證 ,  例如此帳號之前已被註冊過, 命名唯一性
 ```js
 <template>
  <div class="ivu-form-item-error-tip">
    <li v-for="error in props.validate" :key="error.$uid">
      {{ error.$message }}
    </li>
    <li class="customError" v-for="(error, key) in customError" :key="key">
      {{ error }}
    </li>
  </div>
</template>
<script setup lang="ts">
const props = defineProps({
  validate: {
    type: Object,
    default: () => ({}),
  },
  customError: {
    type: Array,
    default: () => [],
  },
});
</script>
<style lang="sass" scoped>
.customError
  display: flex
  justify-content: left
.ivu-form-item-error-tip
  position: relative
  top: 0

li
  color: #ed4014
  margin-top: 5px
</style>
```

- 步驟三

檢查hook 中 是否有 `useValidate.ts`

```js
import { ref } from 'vue';
import { useVuelidate } from '@vuelidate/core';
import {
  minLength,
  maxLength,
  required,
  email,
  sameAs,
  alphaNum,
  helpers,
} from '@vuelidate/validators';

export function useValidate() {
  const maxNameLength = ref(20); // 限制字數不得超過10位數用
  const minNameLength = ref(2); // 限制字數不得超過2位數用
  const maxDescriptionLength = ref(100); // 限制字數不得超過100位數用

  const alphabetAndChinese = (value: any) => {
    const re = /^[A-Za-z0-9\u4e00-\u9fa5]+$/;
    return re.test(value);
  };

  const alphabetAndDash = (value: any) => {
    const re = /^[A-Za-z0-9-]+$/;
    return re.test(value);
  };
  // 擴充客製化的驗證可新增於此
  const rules = {
    email: {
      required: helpers.withMessage('不得為空', required),
      email: helpers.withMessage('Email格式錯誤', email),
    },
    required: {
      required: helpers.withMessage('不得為空', required),
    },
    password: {
      required: helpers.withMessage('不得為空', required),
    },
    sameAsPassword(password: any) {
      return {
        required: helpers.withMessage('不得為空', required),
        sameAs: helpers.withMessage('需與密碼一致', sameAs(password)),
      };
    },
    account: {
      required: helpers.withMessage('不得為空', required),
      maxLength: helpers.withMessage(
        `限制長度不得超過${maxNameLength.value}位`,
        maxLength(maxNameLength)
      ),
      minLength: helpers.withMessage(
        `限制長度不得少於${minNameLength.value}位`,
        minLength(minNameLength)
      ),
    },
    type: {
      alphabetAndDash: helpers.withMessage(
        `限制只能英文與數字與${' "-" 符號'}`,
        alphabetAndDash
      ),
      required: helpers.withMessage('不得為空', required),
      maxLength: helpers.withMessage(
        `限制長度不得超過${maxNameLength.value}位`,
        maxLength(maxNameLength)
      ),
      $lazy: true,
    },
    description: {
      maxLength: helpers.withMessage(
        `限制長度不得超過${maxDescriptionLength.value}位`,
        maxLength(maxDescriptionLength)
      ),
    },
  };

  const v$: any = useVuelidate();

  return {
    rules,
    v$,
  };
}
```

- 步驟四 

**使用方式教學**

```js
import { useValidate } from 'src/hook/useValidate';
import { sameAs, helpers } from '@vuelidate/validators';
const { rules } = useValidate(); // 預設的驗證規範可從rule << 此處領取使用
```

範例:
```js
export default defineComponent({
  name: 'RegisterPage',
  components: {
    Error,
  },
  validations() {
    return {
      formData: {
        account: rules.account,
        password: rules.password,
        confirm_password: rules.sameAsPassword(this.formData.password),
        fullname: rules.required,
        email: rules.email,
        contacts: {
          contact1: rules.required,
        },
      },
    };
  },
  setup() {
    let { v$ } = useValidate();
    const steps = ref(1);
    const $q = useQuasar();

    let formData = ref({
      account: '',
      password: '',
      confirm_password: '',
      fullname: '',
      agent_id: 2002,
      ref_id: 1,
      email: '',
      phone: '',
      contacts: {
        contact1: '',
      },
    });

    const onSubmit = async () => {
      $q.loading.show();
      const isFormCorrect = await v$.value.$validate();
      if (!isFormCorrect) {
        $q.loading.hide();
        return;
      }
      await register(formData.value)
        .then(async (res: any) => {
          if (res.code === 0) {
            // const resData = res.data;
            // sessionStorage.setItem('token', resData.access_token);
            $q.loading.hide();
            // await updatedUserInfo();
            steps.value = 3;
          } else {
            $q.loading.hide();
          }
        })
        .catch(() => {
          $q.loading.hide();
        });
    };

    return { steps, formData, onSubmit, v$ };
  },
});
```


-  結論

簡而言之:  就是利用 `v$.value.$validate()`去觸發改變$dirty狀態 true/false,  另外記得把想要放入驗證的表單放入validations() 中
```js
  validations() {
    return {
      formData: {
        account: rules.account,
        password: rules.password,
        confirm_password: rules.sameAsPassword(this.formData.password),
        fullname: rules.required,
        email: rules.email,
        contacts: {
          contact1: rules.required,
        },
      },
    };
  },
```

另外想要新增驗證只需要到useValidate 新增即可,  可以客製化正規化內容

