是的,模式验证密码和确认密码不起作用

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();

在这里,它创建了一个密码为123456的普通用户

在这里它应该可以工作,因为旧的密码与创建用户的密码相同,它应该更新新的密码

我想尝试了解如何使他明白当前的密码作为旧密码和更新密码

69803 次浏览

Try this out:

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')
});

Based on @anoNewb answer and the request made by @Renan,

Yup.object({
password: Yup.string().required('Password is required'),
passwordConfirmation: Yup.string()
.test('passwords-match', 'Passwords must match', function(value){
return this.parent.password === value
})
})

This is how I did it.

yup.object({
password: yup
.string()
.required('Please enter your password.')
.min(8, 'Your password is too short.'),
retypePassword: yup
.string()
.required('Please retype your password.')
.oneOf([yup.ref('password')], 'Your passwords do not match.')
});