简体   繁体   中英

How to make common validator for both server and client side in nodejs?

I am using https://github.com/chriso/validator.js plugin and I wanted to make a common validation file that I can use for both frontend and server side in node.js. I created a js file and use this code to implement the above.

(function (name, definition) {
    if (typeof exports !== 'undefined' && typeof module !== 'undefined') {
        var validator  = require('../vendor/validator-js/validator');
        module.exports = definition(validator);
    } else if (typeof define === 'function' && typeof define.amd === 'object') {
        define(['validator'], definition(validator));
    } else {
        this[name] = definition();
    }
})('validation-rules', function (Validator) {



'use strict';

/**
 You can write your own custom validation rules here.
 To include new Validation Method to existing Validation JS module
 you can add method like this
Validator.extend('test', function(){
    return true;
});

*/


/**
* [isValidName Check a name is valid or not]
* @param  {[type]}
* @return {Boolean}
*/
Validator.extend('isValidName', function(str){
    return (Validator.isAlpha(str) && Validator.isLength(str, 5,      100));
return Validator;

});

Now when I include this file in client side using require, It give me error that validationrule is not defined. I included both files in main.js require file

validator: 'vendor/validator-js/validator',
validationrules: 'utils/validation-rules',

and in login.js file I included it like

define(['validator','validationrules',  
    ], function(validator,validationrules,){

But when I console validationrules it gives undefined.

I did it as follows

(function(definition) {
    if (typeof exports !== 'undefined' && typeof module !== 'undefined') {
        var validator = require('../vendor/validator-js/validator');
        module.exports = definition(validator);
    } else if (typeof define === 'function' && typeof define.amd === 'object') {
        define(['validator'], function(validator) {
            return definition(validator);
        });
    }
})(function(Validator) {

---- further code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM