How to use validator

Comprehensive validator code examples:

How to use validator.js:

65
66
67
68
69
70
71
72
73
74
75
76
77
78
    });
    return error;
};




// some extension of validator.js


var positiveInt = /^(?:0|[1-9][0-9]*)$/;


validator.isPositiveInt = validator.isId = function(str) {

How to use validator.default:

8
9
10
11
12
13
14
15
16
17
 * @param {string} urlValidatorSettings - settings used by validator
 * @return {boolean} boolean value if the url is valid
 *
 */
function isUrlValid(url, urlValidatorSettings) {
    return typeof url === 'string' && url.length > 0 && validator_1.default.isURL(url, urlValidatorSettings);
}
exports.isUrlValid = isUrlValid;
/**
 * Forces url to start with http:// if it doesn't

How to use validator.prototype:

25
26
27
28
29
30
31
32
33
34
*      birth : Date
*  });
*
* 2. type
*
*  all the type is define in node-validator,  Validator.prototype.is*
*
*  there are isDate, isEmail, isCreditCard, isUrl, etc
*
*  you can use capitalised string or lowercase string. e.g. 'date', 'Email', 'CreditCard', 'url'

How to use validator.check:

2
3
4
5
6
7
8
9
10
11
 */

var nodeValidator = require('validator'),
        util         = require('util'),
        defaultError = nodeValidator.defaultError,
        check        = nodeValidator.check;


var validator = {
        isEmail: function(msg){

How to use validator.len:

96
97
98
99
100
101
102
103
104
105
'before'        : validator.isBefore,

'equals'        : validator.equals,
'contains': validator.contains,
'notContains': function (x, str) { return !validator.contains(x, str); },
'len'                   : function (x, min, max) { return validator.len(x, min, max); },
'in'                    : validator.isIn,
'notIn'         : function (x, arrayOrString) { return !validator.isIn(x, arrayOrString); },
'max'                   : function (x, val) {
        var number = parseFloat(x);

How to use validator.isVariableWidth:

197
198
199
200
201
202
203
204
205
206
  }
  return true;
},
isVariableWidth: function(rule, value) {
  if (rule) {
    return validator.isVariableWidth(value);
  }
  return true;
},
isSurrogatePair: function(rule, value) {

How to use validator.isUppercase:

92
93
94
95
96
97
98
99
100
101
  }
  return true;
},
isUppercase: function(rule, value) {
  if (rule) {
    return validator.isUppercase(value);
  }
  return true;
},
isInt: function(rule, value) {

How to use validator.isFullWidth:

185
186
187
188
189
190
191
192
193
194
  }
  return true;
},
isFullWidth: function(rule, value) {
  if (rule) {
    return validator.isFullWidth(value);
  }
  return true;
},
isHalfWidth: function(rule, value) {

How to use validator.isMultibyte:

173
174
175
176
177
178
179
180
181
182
  }
  return true;
},
isMultibyte: function(rule, value) {
  if (rule) {
    return validator.isMultibyte(value);
  }
  return true;
},
isAscii: function(rule, value) {

How to use validator.isHalfWidth:

191
192
193
194
195
196
197
198
199
200
  }
  return true;
},
isHalfWidth: function(rule, value) {
  if (rule) {
    return validator.isHalfWidth(value);
  }
  return true;
},
isVariableWidth: function(rule, value) {

How to use validator.isBase32:

25
26
27
28
29
30
31
32
33
34
this.isAscii = (subject) => {
    return StringValidator.isAscii(subject) ? null : subject + ' is not ascii';
}

this.isBase32 = (subject) => {
    return StringValidator.isBase32(subject) ? null : subject + ' is not base32';
}

this.isBase64 = (subject) => {
    return StringValidator.isBase64(subject) ? null : subject + ' is not base64';

How to use validator.isBIC:

41
42
43
44
45
46
47
48
49
50
this.isBoolean = (subject) => {
    return StringValidator.isBoolean(subject) ? null : subject + ' is not boolean';
}

this.isBIC = (subject) => {
    return StringValidator.isBIC(subject) ? null : subject + ' is not BIC(Bank Idenfication Code) or SWIFT code.';
}

this.isCreditCard = (subject) => {
    return StringValidator.isCreditCard(subject) ? null : subject + ' is not a Credit Card';

How to use validator.isSurrogatePair:

203
204
205
206
207
208
209
210
211
212
  }
  return true;
},
isSurrogatePair: function(rule, value) {
  if (rule) {
    return validator.isSurrogatePair(value);
  }
  return true;
},
isMongoId: function(rule, value) {

How to use validator.empty:

203
204
205
206
207
208
209
210
211
212
}

// validate boolean columns
if (Object.prototype.hasOwnProperty.call(schema[tableName][columnKey], 'type')
    && schema[tableName][columnKey].type === 'bool') {
    if (!(validator.isBoolean(strVal) || validator.empty(strVal))) {
        message = i18n.t('notices.data.validation.index.valueMustBeBoolean', {
            tableName: tableName,
            columnKey: columnKey
        });

How to use validator.isSomething:

304
305
306
307
308
309
310
311
312
313
    validationOptions = [validationOptions];
}

validationOptions.unshift(value);

// equivalent of validator.isSomething(option1, option2)
if (validator[validationName].apply(validator, validationOptions) !== goodResult) {
    // CASE: You can define specific translations for validators e.g. isLength
    if (i18n.doesTranslationKeyExist('notices.data.validation.index.validationFailedTypes.' + validationName)) {
        translation = i18n.t('notices.data.validation.index.validationFailedTypes.' + validationName, _.merge({

How to use validator.isDivisibleBy:

110
111
112
113
114
115
116
117
118
119
  }
  return true;
},
isDivisibleBy: function(rule, value) {
  if (rule) {
    return validator.isDivisibleBy(value, rule);
  }
  return true;
},
isByteLength: function(rule, value) {

How to use validator.isNull:

192
193
194
195
196
197
198
199
200
201

validations.isNull = function isNull(paramName, customMessage) {
  return checkParam(
    paramName,
    customMessage || message(paramName, 'should be null'),
    validator.isNull
  );
}

validations.isNumeric = function isNumeric(paramName, customMessage) {

How to use validator.toIntFix:

81
82
83
84
85
86
87
88
89
90
hexcolor: {
  method: 'isHexColor'
},
int: {
  method: 'isInt',
  sanitizer: V.toIntFix
},
ip: {
  method: 'isIP'
},

How to use validator.toFloatFix:

71
72
73
74
75
76
77
78
79
80
fqdn: {
  method: 'isFQDN'
},
float: {
  method: 'isFloat',
  sanitizer: V.toFloatFix
},
hex: {
  method: 'isHexadecimal'
},

How to use validator.isJWT:

335
336
337
338
339
340
341
342
343
344
// check if value is a valid email
else if (type === 'email')
    return validator.isEmail(value ?? "")
//  check if value is a jwt
else if (type === 'jwt')
    return validator.isJWT(value ?? "")
// check if value is a valid mongodb id
else if (type === 'mongoid') {
    return validator.isMongoId(String(value ?? ""))
}

How to use validator.isLowercase:

How to use validator.isIn:

98
99
100
101
102
103
104
105
106
107
req.sanitizeBody('secret').trim()
req.sanitizeBody('active').toBoolean()
req.checkBody(webhookSchema)
req.checkBody('labels', 'Invalid label filter (should be a label ID)').optional().isArrayOf(validator.isHexadecimal)
req.checkBody('events', 'Invalid event filter (should be create, update or delete)').optional().isArrayOf(item => {
  return validator.isIn(item, ['create', 'update', 'delete'])
})
const validationErrors = req.validationErrors(true)
if (validationErrors) {
  return next(new errors.BadRequest(null, validationErrors))

How to use validator.isIPRange:

777
778
779
780
781
782
783
784
785
786
          result.remoteAddr ? `${result.remoteAddr}/32` : null
        ]
      : f.trim()
  )
  .flat()
  .filter(f => f && typeof f === 'string' && isIPRange(f))

const debugInfo = {
  host,
  effectiveFirewall,

How to use validator.isLongitude:

38
39
40
41
42
43
44
45
46
  // Turn "a,b" into an array instead of a string
  if (typeof value === 'string') value = value.split(',');

  if (!_.isArray(value)) return false;

  return validator.isLongitude(value[0]) && validator.isLatitude(value[1]);
});
validator.extend('isLatitude', (value) => validator.isFloat(value) && value >= -90 && value <= 90);
validator.extend('isLongitude', (value) => validator.isFloat(value) && value >= -180 && value <= 180);

How to use validator.apply:

40
41
42
43
44
45
46
47
48
    return {
      field: paramName,
      message: message,
      result:
        typeof param !== 'undefined' &&
        validator.apply(null, [param + ''].concat(extraArgs))
    }
  }
}

How to use validator.isExist:

68
69
70
71
72
73
74
75
76
77
 * @param obj
 * @param property
 * @returns {boolean}
 */
validator.isExistAndNotEmpty = (obj, property) => {
  return validator.isExist(obj, property) && validator.isNotEmpty(obj[property])
}

module.exports = {
  /**

How to use validator.isOctal:

79
80
81
82
83
84
85
86
87
88
89
90
91
92
93


const validInt = url => validator.isInt(url);


const validNumber = url => validator.isNumeric(url);


const validOctal = url => validator.isOctal(url);


const validHexa = url => validator.isHexadecimal(url) || validator.isHexColor(url);


const validHexadecimal = url => validator.isHexadecimal(url);

How to use validator.isMongoId:

338
339
340
341
342
343
344
345
346
347
    //  check if value is a jwt
    else if (type === 'jwt')
        return validator.isJWT(value ?? "")
    // check if value is a valid mongodb id
    else if (type === 'mongoid') {
        return validator.isMongoId(String(value ?? ""))
    }
    else
        return false
}

How to use validator.isCurrency:

15
16
17
18
19
20
21
22
23
24
exports.isNumeric = function (value) {
  return validator.isNumeric(value) || validator.isDecimal(value)
}

exports.isCurrency = function (value) {
  return validator.isCurrency(value)
}

exports.isGreaterThanZero = function (value) {
  return value > 0