How to use validator - 10 common examples

To help you get started, we’ve selected a few validator examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github pro-grid / pro-grid / test / spec / server / server-tests.js View on Github external
function validateData(data, dimensions) {
    // yeah so what it's a long return statement why you talkin shit
    return validator.isInt(data.row) && validator.isInt(data.col) && validator.isHexColor(data.color) && data.row < dimensions && data.col < dimensions;
  }
github vpdb / server / src / users / user.api.ts View on Github external
if (!ctx.state.appToken || ctx.state.tokenType !== 'provider') {
			throw new ApiError('Resource only available with provider token.').status(400);
		}
		provider = ctx.state.appToken.provider;

		// validations
		let err = null;
		if (!ctx.request.body.provider_id) {
			err = (err || new ApiError()).validationError('provider_id', 'Identifier at provider is required.');
		} else if (!isString(ctx.request.body.provider_id) && !isNumber(ctx.request.body.provider_id)) {
			err = (err || new ApiError()).validationError('provider_id', 'Identifier at provider must be a number or a string.');
		}
		if (!ctx.request.body.email || !isString(ctx.request.body.email)) {
			err = (err || new ApiError()).validationError('email', 'Email is required.');

		} else if (!validator.isEmail(ctx.request.body.email)) {
			err = (err || new ApiError()).validationError('email', 'Email is invalid.');
		}
		if (!ctx.request.body.username) {
			err = (err || new ApiError()).validationError('username', 'Username is required.');
		} else if (!isString(ctx.request.body.username)) {
			err = (err || new ApiError()).validationError('username', 'Username must be a string.');
		} else if (!/^[0-9a-z ]{3,}$/i.test(UserUtil.removeDiacritics(ctx.request.body.username).replace(/[^0-9a-z ]+/gi, ''))) {
			err = (err || new ApiError()).validationError('username', 'Username must be alphanumeric with at least three characters.', ctx.request.body.username);
		}
		if (ctx.request.body.provider_profile && !isObject(ctx.request.body.provider_profile)) {
			err = (err || new ApiError()).validationError('provider_profile', 'Must be an object.');
		}
		if (err) {
			throw err;
		}
github lzyzsd / androidcn.org / controllers / sign.js View on Github external
nickname = loginname;
  }

  // 验证信息的正确性
  if ([loginname, nickname, pass, rePass, email].some(function (item) { return item === ''; })) {
    ep.emit('prop_err', '信息不完整。');
    return;
  }
  if (loginname.length < 5) {
    ep.emit('prop_err', '用户名至少需要5个字符。');
    return;
  }
  if (!tools.validateId(loginname)) {
    return ep.emit('prop_err', '用户名不合法。');
  }
  if (!validator.isEmail(email)) {
    return ep.emit('prop_err', '邮箱不合法。');
  }
  if (pass !== rePass) {
    return ep.emit('prop_err', '两次密码输入不一致。');
  }
  // END 验证信息的正确性


  User.getUsersByQuery({'$or': [
    {'loginname': loginname},
    {'nickname': nickname},
    {'email': email}
  ]}, {}, function (err, users) {
    if (err) {
      return next(err);
    }
github schahriar / Galleon / seascape / routes / users.js View on Github external
password: req.param('password')
	}

	// REGEX to match:
	// * Between 4 to 64 characters
	// * Special characters allowed (_)
	// * Alphanumeric
	// * Must start with a letter
	if(!validator.isEmail(user.email))
		return res.status(500).json({ error: "Invalid Email", code: "!U" });

	// REGEX to match:
	// * Between 2 to 256 characters
	// * Special characters allowed (&)
	// * Alpha
	if((!validator.matches(user.name, /^([ \u00c0-\u01ffa-zA-Z-\&'\-])+$/))&&(validator.isLength(user.name,2,256)))
	   return res.status(500).json({ error: "Invalid Name", code: "!N" });

	// REGEX to match:
	// * Between 6 to 20 characters
	// * Special characters allowed (@,$,!,%,*,?,&)
	// * Alphanumeric
	if(!validator.matches(user.password, /^(?=.*[a-zA-Z])[A-Za-z\d$@$!%*?&]{6,20}/))
		return res.status(500).json({ error: "Invalid Password", code: "!P" });

	bcrypt.hash(user.password, 10, function(error, hash) {
		if(error) return res.status(500).json({ error: error });
		
		console.log(hash);
		req.database.models.users.create({
			email: user.email,
			name: user.name,
github mtrifilo / react-ssr-boilerplate / server / validation / signupFormValidation.js View on Github external
if (typeof password !== 'string') {
    console.error(
      'validateConfirmPassword: password must be a string. received:',
      typeof password
    )
    return { confirmPassword: 'confirmPassword validation failed' }
  }
  if (typeof confirmPassword !== 'string') {
    console.error(
      'validateConfirmPassword: confirmPassword must be a string. received:',
      typeof confirmPassword
    )
    return { confirmPassword: 'confirmPassword validation failed' }
  }
  // confirmPassword shouldn't be empty
  if (Validator.isEmpty(confirmPassword)) {
    return { confirmPassword: 'Please confirm your password' }
  }
  // password and confirmPassword should match
  if (!Validator.equals(password, confirmPassword)) {
    return { confirmPassword: "Passwords don't match, try again" }
  }
  return { confirmPassword: '' }
}
github DFEAGILEDEVOPS / MTC / admin / lib / validator / check-window / check-window-check-end-date-validator.js View on Github external
module.exports.validate = (validationError, checkEndDateData) => {
  const currentYear = moment.utc().format('YYYY')
  // Check end day
  const isCheckEndDayEmpty = isEmpty(checkEndDateData.checkEndDay.trim())
  if (isCheckEndDayEmpty) {
    validationError.addError('checkEndDay', checkWindowErrorMessages.checkEndDayRequired)
  }
  if (!isCheckEndDayEmpty && !isInt(checkEndDateData.checkEndDay, { min: 1, max: 31 })) {
    validationError.addError('checkEndDay', checkWindowErrorMessages.checkEndDayWrongDay)
  }
  if (!isCheckEndDayEmpty && !XRegExp('^[0-9]+$').test(checkEndDateData.checkEndDay)) {
    validationError.addError('checkEndDay', checkWindowErrorMessages.checkEndDayInvalidChars)
  }
  // Check end month
  const isCheckEndMonthEmpty = isEmpty(checkEndDateData.checkEndMonth.trim())
  if (isCheckEndMonthEmpty) {
    validationError.addError('checkEndMonth', checkWindowErrorMessages.checkEndMonthRequired)
  }
  if (!isCheckEndMonthEmpty && !isInt(checkEndDateData.checkEndMonth, { min: 1, max: 12 })) {
    validationError.addError('checkEndMonth', checkWindowErrorMessages.checkEndMonthWrongDay)
  }
  if (!isCheckEndMonthEmpty && !XRegExp('^[0-9]+$').test(checkEndDateData.checkEndMonth)) {
    validationError.addError('checkEndMonth', checkWindowErrorMessages.checkEndMonthInvalidChars)
  }
  // Check end year
  const isCheckEndYearEmpty = isEmpty(checkEndDateData.checkEndYear.trim())
  if (isCheckEndYearEmpty) {
    validationError.addError('checkEndYear', checkWindowErrorMessages.checkEndYearRequired)
  }
  if (!isCheckEndYearEmpty && !isInt(checkEndDateData.checkEndYear, { min: currentYear, max: (currentYear * 1 + 10) })) {
    validationError.addError('checkEndYear', checkWindowErrorMessages.checkEndYearWrongDay)
github DFEAGILEDEVOPS / MTC / admin / lib / validator / file-validator.js View on Github external
if (!uploadedFile || !uploadedFile.file) {
    validationError.addError(element, fileErrorMessages.noFile)
    return validationError
  }
  if (uploadedFile.file.split('.').pop() !== 'csv') {
    validationError.addError(element, fileErrorMessages.noCSVFile)
    return validationError
  }
  // File not readable
  let fileContent, unreadable
  try {
    fileContent = await fs.readFileSync(uploadedFile.file, 'utf8')
  } catch (err) {
    unreadable = true
  }
  if (isEmpty(fileContent) || unreadable) {
    validationError.addError(element, fileErrorMessages.isNotReadable)
  }
  return validationError
}
github isaychris / reddit-clone / routes / auth.js View on Github external
return function (req, res, next) {
    // make input not case sensitive
    req.body.username = req.body.username.toLowerCase();
    req.body.password = req.body.password.toLowerCase();

    if (
      validator.isAlphanumeric(req.body.username)
    ) {
      console.log("authentication = " + req.isAuthenticated());
      return next();
    }
    res.render("./auth/auth_register", {
      message: "Invalid input. Try again."
    })
  }
}
github devarchy / website / server / database / thingdb / validate / thing.js View on Github external
return;
        }

        if( value === undefined ) {
            errors.push('property `'+prop+'` is equal to `undefined` which is forbidden');
            return;
        }

        assert(prop_spec.validation);

        // TODO - implement validation for type 'Thing.resource', ...
        assert(prop_spec.validation.type);
     // const eraser_value = [null, undefined];
        const eraser_value = [null];
        if( [String, Array].includes( prop_spec.validation.type.constructor ) ) {
            if( !eraser_value.includes(value) && (!value || value.constructor!==String || !validator.isUUID(value)) ) {
                errors.push('property `'+prop+'` has value `'+value+'` but value is expected to be a UUID');
            }
        }
        else {
            // TODO properly handle unserialze Date from DB (problem: JSON saves Date as String -> same for json_data)
            const types = prop_spec.validation.type === Date ? [Date, String] : [prop_spec.validation.type];
            if( !eraser_value.includes(value) && !types.includes(value.constructor) ) {
                errors.push('property `'+prop+'` has value `'+value+'` but value is expected to be a '+prop_spec.validation.type);
            }
        }

        let test = prop_spec.validation.test;
        if( test ) {
            if( ! test(value, {Thing: arg.Thing}) ) {
                errors.push('property `'+prop+'` with value `'+value+'` failed validation test provided by schema');
            }
github doramart / DoraCMS / routes / index.js View on Github external
router.get('/:defaultUrl', function (req, res, next) {

    var defaultUrl = req.params.defaultUrl;
    var url = defaultUrl.split('___')[1];
    var indexUrl = defaultUrl.split('—')[0];
    if (indexUrl == 'page') { // 首页的分页
        var indexPage = defaultUrl.split('—')[1].split(".")[0];
        if(indexPage && validator.isNumeric(indexPage)){
            req.query.page = indexPage;
        }
        siteFunc.renderToTargetPageByType(req,res,'index');
    } else {
        var currentUrl = url;
        if (url) {
            if(url.indexOf("—") >= 0){
                currentUrl = url.split("—")[0];
                var catePageNo = (url.split("—")[1]).split(".")[0];
                if(catePageNo && validator.isNumeric(catePageNo)){
                    req.query.page = catePageNo;
                }
            }
            queryCatePage(req, res, currentUrl);
        }else{
            next();