Easy data validation with Yup
- 2024/7/12
- ブログ
- 2024, Javascript, Yup, ブログ
- Easy data validation with Yup はコメントを受け付けていません
Yup is a JavaScript schema builder for value parsing and validation. It’s commonly used in web applications to validate form inputs, ensuring that the data meets certain criteria before being processed or sent to a server.
Features
Schema definition: Yup allows you to define schemas to describe the shape and type of your data. There are several data types (string, number, array, object, etc.) and some built-in constraints.
Asynchronous validation: Yup supports asynchronous validation, which is useful for scenarios like validating a unique email address.
Custom messages: You can set custom error messages for each validation rule. This helps users understand what went wrong easily.
Transformation: Yup can also transform input values to desired type or format them.
Integration: Yup integrates well with other libraries and frameworks, such as Formik or React Hook Form.
Installing
Yup can be installed by using node.js package managers like npm or yarn.
Command (bash or cmd):
npm install -S yup
or
yarn add yup
Usages
Common
You will define a schema and use it for validation.
import * as Yup from "yup"; const userRegisterSchema = Yup.object().shape({ email: Yup.string() .required("Please input your email address!") .email("Please input correct email address!"), password: Yup.string() .required("Please input your password!") .min(8, "Password must have at least 8 characters!"), age: Yup.number() .typeError("Please input number!") .required("Please input your age!") .positive("Age must be a positive number!"), }); const testData = { email: "someone@example.com", password: "Pass12", age: 25, }; userRegisterSchema.validate(testData).then((value) => { console.log(value); }).catch((error) => { console.log(error.errors);//Result: ["Password must have at least 8 characters."] });
Advanced
Custom validation .test():This function allows you to write custom test code for this field.
.test("number-range", "Please input age between 12 and 75!", (v) => { if (!isNaN(v)) return true; return v >= 12 && v <= 75; })
Conditional validation .when():This is used when this field validation depends on other fields.
qualification: Yup.string().when("age", ([age], schema) => { if (age > 18) { return schema.required("Please input your qualification!"); } return schema; })
Form integration
I will use react-hook-form in this example. Yup can’t be set directly to react-hook-form. You will need a resolver library for it.
Install
npm install -S react-hook-form @hookform/resolvers
or
yarn add react-hook-form @hookform/resolvers
A react form using Yup schema
import { yupResolver } from "@hookform/resolvers/yup"; import { FC } from "react"; import { useForm } from "react-hook-form"; import * as Yup from "yup"; const userRegisterSchema = Yup.object().shape({ email: Yup.string() .required("Please input your email address!") .email("Please input correct email address!"), password: Yup.string() .required("Please input your password!") .min(8, "Password must have at least 8 characters!"), age: Yup.number() .typeError("Please input number!") .required("Please input your age!") .positive("Age must be a positive number!"), }); export const ReactHookForm: FC = () => { const { register, handleSubmit, formState: { errors }, } = useForm({ mode: "onChange", resolver: yupResolver(userRegisterSchema), defaultValues: { email: "", password: "", age: 0, }, }); return ( <form style={{ display: "flex", flexDirection: "column", gap: 8, padding: 12 }} onSubmit={handleSubmit((data) => { //validated data console.log(data); })} > <h3>User Registration</h3> <div>Email:</div> <input placeholder={"email"} {...register("email")} /> {errors.email && ( <div style={{ color: "red" }}>{errors.email.message}</div> )} <div>Password:</div> <input type={"password"} placeholder={"password"} {...register("password")} /> {errors.password && ( <div style={{ color: "red" }}>{errors.password.message}</div> )} <div>Age:</div> <input placeholder={"age"} {...register("age")} /> {errors.age && <div style={{ color: "red" }}>{errors.age.message}</div>} <button type={"submit"}>Submit</button> </form> ); };
Below is the result of the above code. We can see error displays on the left and a valid form on the right.
Summary
With a few settings you can create your own data/form value validator using Yup. Form library integration is also easy. You don’t have to spend a lot of time on writing functions for validating every field. You can check the reference part for more detail about Yup properties.
Reference:
GitHub – jquense/yup: Dead simple Object schema validation
カテゴリー: