如何使用 Yup 验证字符串数组

如何使用 yup 验证字符串数组

你好!在本教程中,您将学习如何使用 yup 验证库验证字符串数组。首先,您将学习如何验证字符串,然后将其应用于数组。我最近遇到了这个问题,表单要求每个输入字段不能为空。我将在本教程中分享我是如何做到的。

什么是是?

yup 是一个流行的、简单的、开源的、用于 javascript(和 typescript)的运行时验证库。 yup 是一个 javascript 模式验证库,它提供了一种以声明性且易于使用的方式定义和验证数据模式的方法。它通常用于前端开发,特别是表单和数据输入验证。开发人员可以使用 yup 的 api 创建验证模式,指定他们期望的数据的形状和约束。

介绍

假设,您正在实现一个用户可以输入多个电子邮件的表单。您必须检查每封电子邮件是否有效,但如何实际创建一个架构,其中每封电子邮件都被验证为电子邮件?

import { object, string, array } from 'yup'const schema = object({  emails: array() //how do you validate each email in the array as an actual email? });

登录后复制

如何验证字符串

要验证 yup 中的字符串,您必须使用 string() 函数,以及其他函数。

例如,如果您需要有效的电子邮件,您可以使用 string().email().

import { object, string, array } from 'yup'const schema = object({  email: string().email()});const isvalid = schema.isvalidsync({    emails: ["", "@test.com"],  });console.log(isvalid); //true which is wrong since they are clearly not emails

登录后复制

如果需要必填字段,可以使用string().required().

import { object, string, array } from 'yup'const schema = object({  requiredfield: string().required()});

登录后复制

这很简单,现在让我们将其应用到数组。

如何验证 yup 中的字符串数组

要验证 yup 中的字符串数组,您必须使用 array().of() 函数指定要验证的数组类型。例如:

import { object, string, array } from 'yup'//1. create a simple validation schema for the stringconst requiredemail = string().email().required("email is required");//2. apply it to the array().of() functionconst schema = object({  emails: array().of(requiredemail)});

登录后复制

现在,当我们尝试使用一些数据再次测试它时,我们得到了正确的结果:

let isvalid = schema2.isvalidsync({  emails: ["", "@test.com"],});console.log(isvalid); //falseisvalid = schema2.isvalidsync({  emails: ["hi@test.com", "hello@test.com"],});console.log(isvalid); //true

登录后复制

如何验证其他类型的数组

类似地,如果您想验证数字数组或任何类型,您可以使用相同的技术。例如:

import { object, string, array, number, boolean } from "yup";const requiredNumber = number().required();const optionalBoolean = boolean().optional();const user = object({  firstName: string().required(),  lastName: string().required(),});const schema3 = object({  numbers: array().of(requiredNumber), // array of numbers  booleans: array().of(optionalBoolean), //array of booleans  users: array().of(user),  // array of objects});

登录后复制

基本上就是这样!

结论

您学习了如何在使用 yup 时验证字符串数组。您还学习了如何使用 array().of() 函数验证其他类型的数组以及创建复杂的数组模式。无论你能用单个对象做什么,你也可以用数组来做。

以上就是如何使用 Yup 验证字符串数组的详细内容,更多请关注【创想鸟】其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2673015.html

(0)
上一篇 2025年3月7日 13:34:51
下一篇 2025年3月7日 12:04:04

AD推荐 黄金广告位招租... 更多推荐

相关推荐

发表回复

登录后才能评论