Introduction
In this project, you will learn how to implement a custom form validator using Vue.js. The custom form validator allows you to validate form fields and check the validity of the data before the user submits the form.
👀 Preview

🎯 Tasks
In this project, you will learn:
- How to implement the
FormInputcomponent to update thev-modelvalue of the component when the value of the input field changes. - How to implement the
is_emailfunction to validate the email address based on specific rules. - How to implement the
validateFormfunction to validate the form data based on the defined validation rules.
🏆 Achievements
After completing this project, you will be able to:
- Create a custom form validator in Vue.js.
- Validate form fields using custom validation rules.
- Handle form validation errors and display them to the user.
Set Up the Project Structure
In this step, you will set up the project files and structure. Follow the steps below to complete this step:
Open the project folder. The directory structure is as follows:
├── components
│ ├── FormInput.js
│ └── FormValidator.js
├── css
├── index.html
├── js
│ └── util.js
└── lib
└── vue.global.js
Where:
index.htmlis the main page.cssis the folder for storing project styles.libis the folder for storing project dependencies.components/FormInput.jsis theinputcomponent.components/FormValidator.jsis the form validator component.js/util.jsis the utility function required by the project.
Click on Go Live button in the bottom right corner of WebIDE, to run the project.
Next, open "Web 8080" on the top of the VM and manually refresh it to see the page.
Implement the FormInput Component
In this step, you will learn how to implement the FormInput component to update the v-model value of the component in index.html when the value of the input field changes.
Open the
FormInput.jsfile located in thecomponentsdirectory.In the
setupfunction of theFormInputcomponent, find the TODO section for objective 1.Implement the code to trigger an event to update the
v-modelvalue of the component when the value of the input field (with the classform-input) changes.watch(inputValue, (newValue) => { emit("update:modelValue", newValue); });This code uses the
watchfunction to observe changes to theinputValuereactive variable. When the value changes, it emits an event with the new value to update thev-modelbinding in the parent component.Save the changes to the
FormInput.jsfile.
Implement the is_email Function
In this step, you will learn how to implement the is_email function in the util.js file to validate the email address.
Open the
util.jsfile located in thejsdirectory.In the
is_emailfunction, find the TODO section for objective 2.Implement the logic to validate the email address based on the provided requirements:
- The email address must be between 6 and 20 characters long.
- The email address must consist of a username part and a domain part, separated by the
@symbol. - The username part must be at least 1 character long and can contain digits or letters.
- The domain part must contain a
.in the middle, and the part before the.must be at least 1 character long, while the part after the.must be 2 to 4 letters.
Here's an example implementation:
const is_email = (val) => { const emailRegex = /^[a-zA-Z0-9]+@[a-zA-Z0-9]+.[a-zA-Z]{2,4}$/; return emailRegex.test(val); };Save the changes to the
util.jsfile.
Implement the validateForm Function
In this step, you will learn how to implement the validateForm function in the FormValidator.js file to validate the form data.
Open the
FormValidator.jsfile located in thecomponentsdirectory.In the
validateFormfunction, find the TODO section for objective 3.Implement the logic to validate the form data based on the provided
formRulesobject. The validation should follow these rules:- If the
nicknamefield is empty, add an error message to theerrorsobject with the key"nickname". - For the
emailfield:
- If the field is empty, add an error message to the
errorsobject with the key"email". - If the email address does not conform to the rules or is not within the correct length range, add an error message to the
errorsobject with the key"email".
Here's an example implementation:
const validateForm = () => { return new Promise((resolve, reject) => { errors.value = {}; // Clear the previous error message // Validate nickname try { props.rules.nickname.map((item) => { item?.validator(null, props.formData.nickname, (err) => { if (err) { throw "nickname|" + err.message; } }); }); } catch (e) { const parseErr = e.split("|"), errKey = parseErr[0], errValue = parseErr[1]; errors.value[errKey] = errValue; } // Validate email try { props.rules.email.map((item) => { if (item?.required) { if (props.formData.email == "") throw "email|" + item.message; } if (item?.type) { if (!validateByType(item.type, props.formData.email)) throw "email|" + item.message; if (props.formData.email.length < 6) throw "email|" + item.message; if (props.formData.email.length > 20) throw "email|" + item.message; } }); } catch (e) { const parseErr = e.split("|"), errKey = parseErr[0], errValue = parseErr[1]; errors.value[errKey] = errValue; } if (hasErrors.value) { resolve(false); // Error exists, validation failed } else { resolve(true); } emit("valid", errors.value); }); };- If the
Save the changes to the
FormValidator.jsfile.
Congratulations! You have now completed the implementation of the custom form validator. You can now test the application by running the project and interacting with the form. The completed effect is as follows:

Summary
Congratulations! You have completed this project. You can practice more labs in LabEx to improve your skills.



