DEV Community

WebCraft Notes
WebCraft Notes

Posted on • Updated on • Originally published at webcraft-notes.com

Vue 3, Nuxt 3 Form Validation: Creating Simple Custom Input Validator

main title image

Check this post in my blog.

Prerequisites:

  • familiar with Vue js;
  • should be installed Node js and npm;

Introduction:

Every web service requires robust user input validation, whether it's for login credentials, contact details, prices, or quantities in e-commerce websites. While Vue.js offers various validation libraries like VeeValidate, VueValidate, and Vue Formulate, I've encountered certain inconveniences, especially when it comes to updates.

In this post, I'll guide you through creating a straightforward and reusable custom validator in Vue.js. Once you grasp how straightforward it is, you'll be able to implement it seamlessly in all your future projects. Let's simplify form validation together.

Step 1: Prepare our project.

We will not stop for long here, I'll just create a new "test" project according to official Vue js link The project will contain the main start folders and files:

starting project

Then, for example purposes, I will add a "Login" page with two traditional inputs Password and Email.

login template

That's it we finished our preparation and on our next step, we can start working on our validator.

Step 2: Create Validator.

Let's create a folder "validation" with a validator.js file inside, add an exported function, and call it "validator" also. So, we need our validator to accept some values with possible rules, and after checking return a list of objects. Why objects? Because it will be convenient to receive not only status for example but also a short error message.

Okay, we will add the variable "validationResult" that will be our errors container, forEach cycle for the rules array and function "validate()" which will have a small (in my test variant) "switch". "switch" should check rule and in case such rule exist estimate value if it is pass or not. Result of such estimation we will push into the "validationResult" variable. Here how it will look like:

export function validator(value, rules) {
    const validationResult = [];
    rules.forEach(el => validate(value, el))

    function validate(value, rule) {
        switch(rule) {
            case 'email':
                validationResult.push(validateOnEmail(value));
                break;
            case 'required':
                validationResult.push(validateOnRequired(value));
                break;
            case 'password':
                validationResult.push(validateOnPassword(value));
                break;
        }
    }
    return validationResult;
}
Enter fullscreen mode Exit fullscreen mode

Step 3: Create rule checker functions.

Great, we have a validator, and now we can add functions (for replacement "result(value)" function) that will be our rules checkers. Each function should accept value and return a checking result. In my project, the function will return "true" if no error, and an object with "status" and "msg" fields. I immediately answered your question: "Yes, you can return only status (true or false), even return boolean status or string message and it will be fine! Also you can add any additional information you need". Here are my checker functions examples:

function validateOnEmail(value) {
    const emailRegex = /\S+@\S+\.\S+/;
    const result = emailRegex.test(value);

    if(result) {
        return true;
    } else {
        return {
            status: false,
            msg: 'Please check your email!'
        }
    }
}

function validateOnRequired(value) {
    if(value) {
        return true;
    } else {
        return {
            status: false,
            msg: 'Required field!'
        }
    }
}

function validateOnPassword(password) {
    const letterRegex = /[a-zA-Z]/;
    const numberRegex = /[0-9]/;

    if (password.length < 8) {
        return {
            status: false,
            msg: 'Should contain at least 8 characters.'
        }
    }

    if (!letterRegex.test(password) || !numberRegex.test(password)) {
        return {
            status: false,
            msg: 'Should contain minimum one letter and one number.'
        }
    }

    return true;
}
Enter fullscreen mode Exit fullscreen mode

Check full post...

Top comments (0)