Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use React with Yup Validation (Without Formik)

Tags:

reactjs

yup

Any idea how can I do a React input validation using Yup (without Formik)?

I couldn't find online any good example. Thanks

like image 961
Alfrex92 Avatar asked Aug 28 '19 07:08

Alfrex92


People also ask

Can I use Yup without Formik?

Yes, you can use Yup without Formik, and you can use Formik without Yup.

How do you add yup to React?

import React from "react"; import * as Yup from "yup"; const ProductReviewForm = () => { const products = ["Product 1", "Product 2", "Product 3", "Product 4"]; const validationSchema = Yup. object({ product: Yup. string(). required("Please select a product").


1 Answers

You can use cast() if u want to use yup without formik, see example :

let yup = require('yup');

let schema = yup.object().shape({
  name: yup.string().required(),
  age: yup
    .number()
    .required()
    .positive()
    .integer(),
  email: yup.string().email(),
  website: yup.string().url(),
  createdOn: yup.date().default(function() {
    return new Date();
  }),
});

// check validity
schema
  .isValid({
    name: 'jimmy',
    age: 24,
  })
  .then(function(valid) {
    valid; // => true
  });

// you can try and type cast objects to the defined schema
schema.cast({
  name: 'jimmy',
  age: '24',
  createdOn: '2014-09-23T19:25:25Z',
});
// => { name: 'jimmy', age: 24, createdOn: Date }
like image 156
Andre Feri Avatar answered Oct 19 '22 08:10

Andre Feri