React JS form validation using yup library

Install

npm install yup --save

Import

import * as Yup from 'yup';

Build validation Schema

const SignupSchema = Yup.object().shape({
    name: Yup.string()
      .min(2, 'Too Short!')
      .max(50, 'Too Long!')
      .required('Required'),
});

Usage

<Formik
            initialValues={{ 
                name:'',
                password:'',
                cpassword:''
             }}
             validationSchema={SignupSchema}
             onSubmit={async (values)=>{
                 console.log(values);
             }}
>

List of validations

String
.required(message)  
.min(limit: number, message)  
.max(limit: number, message)  
.email(message)  
.url(message)  
Number
.min(limit: number, message)  
.max(limit: number, message)  
.lessThan(max: number, message)  
.moreThan(min: number, message)  
.positive(message)  
.negative(message)  
.integer(message)  
Array
.oneOf([Yup.ref(field_name), null], message)  

Validation for strong password

install

npm install yup-password

Import & extends

import YupPassword from 'yup-password'
YupPassword(yup)

Usage

yup.string().password()
    .minLowercase(8)

.password() has default : at least 8 characters, at most 250 characters, at least 1 lowercase letter, at least 1 uppercase letter, at least 1 number and at least 1 symbol.

© 2016 - 2022, All Rights are Reserved.