Custom Form Validation with Element UI in Vue
This article explains what form validation is, why custom validation rules are needed in Vue projects using Element UI, and provides step‑by‑step code examples for binding rules and models, defining custom validators, and handling rich‑text content validation.
Form validation is a client‑side check performed before submitting data to the server, ensuring fields such as email, phone number, or required inputs meet the expected format.
When built‑in validation rules are insufficient for a project's specific needs, developers can create custom validation rules to enforce additional constraints.
To use custom validation with Element UI, bind the rules and model attributes to the el-form component, and specify the data object to be validated.
<el-form label-position="right" :rules="rules" size="small" ref="formRef" :model="form">
Each form field that requires validation should have a corresponding el-form-item with the prop attribute matching the key in the validation rules.
<el-form-item prop="content"> <Editor v-if="isnextTick" :content="content" :editorRef="editor2" @keydown="(e) => keydownup(e)" @onChangeEdito="onChangeEdito"> </Editor> </el-form-item>
The validation rules are defined using a reactive object. For example, a rule that checks whether the content is not empty and runs a custom validator:
const rules = reactive({ content: [{ required: true, validator: checkSpace, trigger: "blur" }] });
The custom validator must always invoke the callback function, passing an Error when validation fails.
const checkSpace = (rule, value, callback) => { if (!value.trim()) { callback(new Error("发布评论不能为空")); } else { callback(); } };
Additional helper functions can be created to handle more complex checks, such as removing empty HTML paragraphs from rich‑text content:
const checkVal = (str) => { let num = 0; const reg = / ( | \s+)+<\/p>| ( ) +<\/p>/g; while (num < str.length && str !== "") { num++; const k = str.match(reg); if (k) { str = str.replace(k[0], ""); } } return str === ""; };
By defining custom rules like the examples above, developers can tailor form validation to meet the exact requirements of their applications, providing more flexible and reliable user input handling.
360 Quality & Efficiency
360 Quality & Efficiency focuses on seamlessly integrating quality and efficiency in R&D, sharing 360’s internal best practices with industry peers to foster collaboration among Chinese enterprises and drive greater efficiency value.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.