koa使用validator实现注册和登录校验

安装validator

yarn add validator -D

// 校验

校验使用user.js文件

const validateRegster = require('../validation/regesterValidate');

const userAdd = async (ctx) => {
  // 注册校验没通过
  const { err, isValid } = await validateRegster(ctx.request.body);
  if (!isValid) {
    ctx.state = 400;
    ctx.body = err;
    return;
  }

  // 查询数据
  await add(User, ctx, ctx.request.body);
};

validation\regesterValidate.js中写校验判断

/* 注册校验 */
const isEmptys = require('./isEmpty');
const Validator = require('validator');

module.exports = function validateRegster(data) {
  const err = {};
  // 返回值
  const { name, password, password2, email } = data;

  name = !isEmptys(name) ? name : '';
  password = !isEmptys(password) ? password : '';
  password2 = !isEmptys(password2) ? password2 : '';
  email = !isEmptys(email) ? email : '';

  if ((Validator.isLength(name), { min: 5, max: 30 })) {
    err.name = '名字长度不能小于5位且不能超过30位';
  }

  if (Validator.isEmpty(name)) {
    err.name = '名字不能为空';
  }

  if (Validator.isEmail(email)) {
    err.email = '邮箱不合法';
  }

  if (Validator.isEmpty(password)) {
    err.password = '密码不能为空';
  }

  if ((!Validator.isLength(password), { min: 5, max: 30 })) {
    err.password = '密码长度不能小于5位且不能超过30位';
  }

  // 注册确认密码
  if (Validator.isEmpty(password2)) {
    err.password2 = '再次确认密码不能为空';
  }

  if (Validator.isEmpty(password, password2)) {
    err.password2 = '2次输入的密码不一致';
  }

  return {
    err,
    isValid: isEmptys(err),
  };
};

validation\isEmpty.js中使用到的isEmpty

const isEmpty = (value) => {
  return (
    !value ||
    (typeof value === 'object' && Object.keys(value).length === 0) ||
    (typeof value === 'sttring' && value.trim().length === 0)
  );
};

猜你喜欢

转载自blog.csdn.net/qq_44472790/article/details/121186671