'YUP schema validation for existing input
I am trying to create a schema to validate if the entered input is not already in an array. If it is, then i need to log an error to the user. E.g. if the entered input value "apple" is already in some array ["apple", "mango", "banana"] then i need to show the message "Fruit already exists". What's the validation schema for that?
Thanks
Solution 1:[1]
import React, { useState } from "react";
import { Formik, Form, ErrorMessage } from "formik";
import * as Yup from "yup";
const Fruit = (props) => {
// Use State to update the array if required
const [fruits, setFruits] = useState(["apple", "mango", "banana"]);
const validationSchema = Yup.object().shape({
fruit: Yup.string()
.test("fruit", "Fruit already exists", (value) => !fruits.includes(value)) //check if fruit is present in state array
.required("Required"),
});
return (
<>
<Formik
initialValues={{ fruit: "" }}
validationSchema={
validationSchema
}
onSubmit={(val) => { }}
>
{({
handleChange,
handleBlur,
}) => (
<Form>
<input
type="text"
name="fruit"
onChange={handleChange}
onBlur={handleBlur}
/>
<br />
<ErrorMessage name="fruit" />
</Form>
)}
</Formik>
</>
);
};
export default Fruit;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Arfat Binkileb |


