Vue 3 element plus. How to validate form on mount
- User
Vue 3 element plus. How to validate form on mount
- Assistant
Vue 3 element plus. How to validate form on mount
In Vue 3 with Element Plus, validating a form upon component mount (i.e., immediately when the page or component loads) can be a common requirement, especially if you want to show initial validation messages or check the form against preset values. To achieve this, you would typically use the ref attribute to create a reference to the form, and then call its validate method inside the onMounted lifecycle hook. Here's how to do it:
Create the form in your template: Use Element Plus form components to define your form. Ensure each form item has a prop defined that corresponds to the property in your data model that it represents. Also, use the ref attribute to create a reference to the form.
Define a validation rule object: In your Vue component's setup function, define the rules for validation.
Use the onMounted lifecycle hook: Inside onMounted, access the form reference and call its validate method to trigger validation as soon as the component is mounted.
Here's an example to illustrate these steps:
<template>
<el-form ref="formRef" :model="form" :rules="rules">
<el-form-item label="Name" prop="name">
<el-input v-model="form.name"></el-input>
</el-form-item>
<el-form-item label="Email" prop="email">
<el-input v-model="form.email"></el-input>
</el-form-item>
<!-- Add other form items here -->
</el-form>
</template>
<script setup>
import { ref, onMounted } from 'vue';
import { ElForm } from 'element-plus';
const formRef = ref(null);
const form = ref({
name: '',
email: '',
});
const rules = {
name: [
{ required: true, message: 'Please input the name', trigger: 'blur' },
],
email: [
{ required: true, message: 'Please input the email address', trigger: 'blur' },
{ type: 'email', message: 'Please input correct email address', trigger: ['blur', 'change'] },
],
};
onMounted(() => {
formRef.value.validate((valid) => {
if (valid) {
alert('Validation succeeded!');
} else {
console.log('Validation failed!');
return false;
}
});
});
</script>
In this example:
The ref="formRef" attribute creates a reference (formRef) to the form element.
The :model="form" binds the form data to a reactive form object.
The :rules="rules" binds validation rules defined in the rules object.
Inside the onMounted lifecycle hook, the validate method of formRef is called to trigger the validation process.
Make sure you have Element Plus properly imported in your project to use ElForm, ElFormItem, and other components. You can always adjust the validation logic and rules based on your specific requirements.