1.0.3 • Published 3 years ago

@kodinggen/express-validator v1.0.3

Weekly downloads
-
License
MIT
Repository
github
Last release
3 years ago

Express Validator

a simple validator package for validating your form requests.

INSTALLATION

npm install @kodinggen/express-validator --save

USAGE

A Basic Setup

const express = require('express');
const { validation } = require('express-validator');

express.use(validation());

Validating request

When initial setup was done, the validator instance also available on req object. You can build your validation rule using req.validator object. for instance :

app.post('/validation', function(req, res) {

    const { username, email, age, description } = req.body;

    // Build the validation
    const validator = req.validator.build({ username, email, age, description }, {
        username: 'required|string|alpha_numeric',
        email: 'required|string|email',
        age: 'required|integer',
        description: 'optional|string'
    });

    // Validate fields with rules.
    validator.validate().then(function(result) {
         // Check if validation has error for each of rules.
        if (result.status === 'error') {

            // return status 425 and return error all error messages for each rules and fields.
            res.status(425).json(result.data);
        }

        res.end('validation success');
    });
});

We build the validation using req.validator.build() this function will return the Validator instance. first parameter will be your field that need to be validated and second parameter validation rules seperated with |, each given field will check all given rules so the error messages for each field will return array.

validateSync function was method since version 1.0.2, use validate() instead

The validator.validateSync will validate all given fields and fill the error message if validation was fail for given rules.

If you working with session library like express-session is highly recommended using the validate() method, it will return promise to make sure all validation errors is saved to session object. **

Example validation with session

const { validation }  = require('./index');
const app = express();

app.set('view engine', 'ejs');

app.use(session({
    secret: 'flying cat',
    resave: false,
    saveUninitialized: true,
    cookie: { maxAge: 60 * 60 * 60 * 24, httpOnly: false }
}));

app.get('/', function(req, res) {
    return res.render('home');
});

app.post('/validation-session', function(req, res) {
    const { username, email, age, description } = req.body;

    // Build the validator
    const validator = req.validator.build({ username, email, age, description }, {
        username: 'required|string|alpha_numeric',
        email: 'required|string|email',
        age: 'required|integer',
        description: 'optional|string'
    });

    // Validate with rules
    validator.validate().then(function(result) {
        if (result.status === 'error') {
            // If there are validations error redirect to `home` route
            return res.redirect('/home');
        }

        return res.end('validation success');
    }).catch(function(error) {
        return res.end(error);
    });

});

app.listen(3000);

Since version 1.0.2, you will assign the validationErrors object by your self because this package no longer using express-session library for flexibility.

This can be done with:

validator.validate().then(function(result) {
    if (result.status === 'error') {
        // If there are validations error redirect to `home` route
        res.locals.validationErrors = result.data;
        return res.redirect('/home');
    }

    return res.end('validation success');
}).catch(function(error) {
    return res.end(error);
});

Now you can access validationErrors in the view file :

<% if(validationErrors) { %>
    <% if(validationErrors.username) { %>
        <span class="badge badge-danger"><%= validationErrors.username[0] %></span>
    <% } %>
<% } %>

The promise result object will contain two properties status and data, status will contains 'error' or 'success' and data will contains validation error messages if validation fail or return all fields with all value already been trim.

validator.validate().then(function(result) {
    if (result.status === 'error') {
        // If there are validations error redirect to `home` route
        res.status(200).json(result.data) // This will return validation error messages
    }

    if (result.status === 'success) {
        res.status(200).json(result.data) // This will return all fields and its value.
    }

    return res.end('validation success');
}).catch(function(error) {
    return res.end(error);
});

Custom Error Messages

This feature available for version 1.0.2++

Now you can define a custom error message before validation process. For example :

const validator = req.validator.build(req.body, {
    name: 'required|string|min:4',
    email: 'required|string|email',
    content: 'optional'
});

validator.setErrorMessages({
    email: function(fieldName) {
        return `this ${fieldName} field should be a valid email`
    },
    min: function(fieldName, args) {
        return `this ${fieldName} field should have minimal length of ${args[0]}`
    }
});

Available Validation Rules

Rule NameParametersDescriptions
requriednoneField under this rule must be filled in
maxmax_valueField must be have maximum value at given parameter, example usage with parameter max:10 -> if string passed it will match length of given string
minmin_valueField must be have minimum value at given parameter, example usage with parameter min:10 -> if string passed it will match length of given string
stringnoneField under this rule must be type of string
numericnoneField under this rule must be numeric value
alphanoneField under this rule must be alphabetic character
alpha_numericnoneField under this rule must be alphabetic and numeric value
emailnoneField under this rule must be valid email
integernoneField under this rule must be an integer value
optionalnoneThis rule allow some field to be empty
betweenmin,maxField under this rule must have value between given parameters, example usage with parameter between:5,20
urlnoneField under this rule must be valid url
enuma,b,c,...,nField under enum rule must match between enum set enum:example1,example2,example3

API Reference

Method NameParametersReturn ValueDescription
build()nonevalidator instanceinitiate the validation.
hasError()nonebooleancheck if validation has any error from each field.
flashError()nonevoidstore and receive validation messages from the session.
getAllErrors()noneobjectsreturn all errors for each field.
getError()field_nameobjectreturn validation errors for specified field.
validate()nonePromisepromise based validation process, it will store validation error messages on session storage
setErrorMessages()objectvoidset the custom validation error messages

Testing

npm run test

Http test

npm run test-http

1.0.2

3 years ago

1.0.3

3 years ago

1.0.1

4 years ago

1.0.0-alpha

4 years ago