reboottime / WebDevelopment

Some notes, thoughts and articles aggregated here about UI/UX and web development.
6 stars 0 forks source link

Yup schema validation collections #106

Open reboottime opened 1 year ago

reboottime commented 1 year ago
  1. Validate password confirmation
    const userPassSchema = yup.object().shape({
    pwd: yup.string().required("Password is required"),
    confirmPwd: yup.string().oneOf([yup.ref('password')], 'Password and confirm password must match').required('Confirm Password is required field'),
    });
  2. Password should not have any part of user name
    
    const yup = require('yup');

const userSchema = yup.object().shape({ name: yup.string().required(), email: yup.string().email().required(), password: yup.string() .required() .min(8) .test('no-name-in-password', 'Password cannot include the user name', function(value) { const nameParts = this.parent.name.split(' '); for (let i = 0; i < nameParts.length; i++) { if (value.includes(nameParts[i])) { return false; } } return true; }) });

3. Conditional validation: sample code

```ts
const sourceSchema = yup.object().shape({
  auth: yup.object().shape({
    source: yup
      .mixed<AuthSourceType>()
      .oneOf(['google', 'github'])
      .required('Authentication type is required'),
    id: yup.string().test('conditional-validation', '', function (value) {
      const { source: authSource } = this.parent;

      if (authSource === 'google' && !value) {
        return this.createError({
          path: 'auth.id',
          message: 'Google open id is required'
        });
      }

      if (authSource === 'github' && !value) {
        return this.createError({
          path: 'auth.id',
          message: 'Github open id is required'
        });
      }

      return true;
    })
  })
});