欢迎光临
我们一直在努力

如何使用 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 string
const requiredemail = string().email().required("email is required");

//2. apply it to the array().of() function
const schema = object({
  emails: array().of(requiredemail)
});

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

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

isvalid = 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() 函数验证其他类型的数组以及创建复杂的数组模式。无论你能用单个对象做什么,你也可以用数组来做。

赞(0) 打赏
未经允许不得转载:码农资源网 » 如何使用 Yup 验证字符串数组
分享到

觉得文章有用就打赏一下文章作者

非常感谢你的打赏,我们将继续提供更多优质内容,让我们一起创建更加美好的网络世界!

支付宝扫一扫打赏

微信扫一扫打赏

登录

找回密码

注册