简体   繁体   English

如何在Node.js中为服务器端和客户端建立通用验证器?

[英]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. 我正在使用https://github.com/chriso/validator.js插件,我想制作一个通用的验证文件,该文件可用于node.js的前端和服务器端。 I created a js file and use this code to implement the above. 我创建了一个js文件,并使用此代码实现了以上内容。

(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. 现在,当我使用require在客户端中包含此文件时,它给我带来错误,即没有定义validaterule。 I included both files in main.js require file 我在main.js中将两个文件都包括在内

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

and in login.js file I included it like 在login.js文件中,我像这样包含了它

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

But when I console validationrules it gives undefined. 但是,当我控制台validationrules它给出了未定义的信息。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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