是的,架构验证密码和确认密码不起作用 [英] Yup schema validation password and confirmPassword doesn't work

查看:0
本文介绍了是的,架构验证密码和确认密码不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

import * as Yup from 'yup';
import User from '../models/User';

class UserController {
async store(req, res) {
const schema = Yup.object().shape({
  name: Yup.string().required(),
  email: Yup.string()
    .email()
    .required(),
  password: Yup.string()
    .required()
    .min(6),
});

if (!(await schema.isValid(req.body))) {
  return res.status(400).json({ error: 'Validation fails' });
}

const userExists = await User.findOne({ where: { email: req.body.email } });
if (userExists) {
  return res.status(400).json({ error: 'User already exists.' });
}
const { id, name, email, provider } = await User.create(req.body);
return res.json({ id, name, email, provider });
}

async update(req, res) {
const schema = Yup.object().shape({
  name: Yup.string(),
  email: Yup.string().email(),
  oldPassword: Yup.string().min(6),
  password: Yup.string()
    .min(6)
    .when('oldPassword', (oldPassword, field) =>
      oldPassword ? field.required() : field
    ),
  confirmPassword: Yup.string().when('password', (password, field) =>
    password ? field.required().oneOf([Yup.ref('password')]) : field
  ),
});

if (!(await schema.isValid(req.body))) {
  return res.status(400).json({ error: 'Validation fails' });
}

const { email, oldPassword } = req.body;
const user = await User.findByPk(req.userId);
if (user.email !== email) {
  const userExists = await User.findOne({
    where: { email },
  });
  if (userExists) {
    return res.status(400).json({ error: 'User already exists.' });
  }
}

if (oldPassword && !(await user.checkPassword(oldPassword))) {
  return res.status(401).json({ error: 'Password does not match.' });
}

const { id, name, provider } = await user.update(req.body);

return res.json({ id, name, email, provider });
  }  
}
export default new UserController();

here it creates a normal user with the password 123456

here it should work, since the old password is the same as the password of the created user, and it should update the new password

我想试着了解如何让他将当前密码理解为旧密码并更新密码

推荐答案

试用:

import * as Yup from 'yup';

validationSchema: Yup.object({
  password: Yup.string().required('Password is required'),
  passwordConfirmation: Yup.string()
     .oneOf([Yup.ref('password'), null], 'Passwords must match')
});

这篇关于是的,架构验证密码和确认密码不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆