yup是一个npm包,我们可以在react-native应用程序中安装。它用于验证存储在单个对象中的表单值。此外,我们可以使用 yup 将不同类型的验证添加到不同的表单字段。
用户可以在项目目录中执行以下命令来在react native中安装yup。
npm i yup
如果用户使用 yarn,可以使用以下命令。
yarn i yup
语法用户可以按照以下语法在react-native应用程序中使用yup进行表单验证。
const schema = yup.object().shape({ key1: yup.string().required(required),});await schema.validate(values);
在上面的语法中,我们使用 yup 创建了模式,并使用 validate() 方法根据模式中定义的规则来验证值。这里,值是一个包含表单属性名称和值对的对象。
步骤第 1 步 - 首先,开发人员需要从 yup 中导入所需的内容。
步骤 2 - 在 app() 组件中,使用 yup 创建一个“userformschema”,它定义了 student_id、age 和 portfolio 字段的规则。这里,student_id 是一个字符串和必填字段,age 是一个正整数和必填字段,portfolio 是网站的 url。
第 3 步 - 现在,使用“usestate”挂钩定义学生信息和验证消息的状态。
第4步 - 定义handlechange()函数,该函数将键和值作为参数,并更新“initialvalue”状态对象中的值。
第 5 步 - 接下来,定义 validatevalues() 函数,该函数通过将 userformschema 作为引用、将 studentinfo 对象作为参数来使用 validate() 方法来验证表单价值观。
第 6 步 - 根据表单值的验证将消息设置为“消息”状态。
示例 1在下面的示例中,我们创建了一个表单来收集学生信息。我们添加了三个输入字段来获取 student_id、年龄和作品集网站的 url。此外,我们还创建了提交按钮。
每当用户单击提交按钮时,都会调用 validatevalues() 函数,该函数会在屏幕上显示验证消息。
import react, { usestate } from react;import * as yup from yup;import { touchableopacity, view, textinput, text, button } from react-native;const app = () => { // creating the user form schema using yup to validate student_id, age, and portfolio const userformschema = yup.object().shape({ student_id: yup.string().required(required), age: yup.number().required(required).positive().integer(), portfolio: yup.string().url().nullable(), }); const [studentinfo, setstudentinfo] = usestate({ student_id: , age: 13, portfolio: , }); const [message, setmessage] = usestate(); function handlechange(key, val) { setstudentinfo({ ...studentinfo, [key]: val }); } // creating the handleformsubmit function to handle the form submission async function validatevalues() { try { await userformschema.validate(studentinfo); setmessage(form is successfully submitted with no errors!); } catch (error) { console.log(error); setmessage(form is not submitted due to errors!); } } return ( // rendering the form <view style = {{ width: 70% }}> {/* text inputs */} <textinput placeholder = student_id value = {studentinfo.student_id} onchangetext = {(value) => handlechange(student_id, value)} /> <textinput placeholder = age value = {studentinfo.age} onchangetext = {(value) => handlechange(age, value)} /> <textinput placeholder = portfolio value = {studentinfo.portfolio} onchangetext = {(value) => handlechange(portfolio, value)} /> {/* submit button */} <touchableopacity onpress = {validatevalues}> <text> submit form </text> </touchableopacity> <text> {message} </text> </view> );};export default app;
输出
示例 2下面的例子是上面例子的高级版本。在这里,我们有三个输入字段,其中包含用户名、电子邮件和密码。
此外,我们还使用 yup 创建了 userformschema 来验证表单。在这里,我们定义了规则,因此名称的长度应至少为三个字符,并且始终是必需的。电子邮件应遵循格式并始终为必填项,密码长度应至少为六个字符。
此外,我们还为输入字段和错误消息提供了一些样式。当用户单击提交按钮时,它会调用handleformsubmit()函数,该函数通过调用validatevalues()函数来获取验证结果。它显示基于表单验证的输出消息。
import react, { usestate } from react;import * as yup from yup;import { stylesheet, touchableopacity, view, textinput, text,} from react-native;const app = () => { // creating the user form schema using yup to validate name, email and password const userformschema = yup.object().shape({ name: yup.string().min(3, too short).required(required), email: yup.string().email(invalid email).required(required), password: yup.string().min(6, too short).required(required), }); // creating the styles for the elements const elementstyles = stylesheet.create({ container: { flex: 1, alignitems: center, backgroundcolor: aqua, justifycontent: center, }, error: { marginbottom: 10, color: red, }, button: { backgroundcolor: #0084ff, width: 70%, borderradius: 4, alignitems: center, padding: 12, }, input: { borderwidth: 2, padding: 15, marginbottom: 10, width: 70%, bordercolor: green, borderradius: 4, }, buttontext: { color: #fff, fontsize: 16, fontweight: bold, }, }); // creating the state for the form const [initialvalues, setinitialvalues] = usestate({ name: , email: , password: , }); // creating the state for the errors const [errors, seterrors] = usestate({}); const [message, setmessage] = usestate(); // creating the handlechange function to handle the change in the input fields function handlechange(key, val) { setinitialvalues({ ...initialvalues, [key]: val }); } // creating the validatevalues function to validate the form async function validatevalues() { try { // validating the form using the userformschema await userformschema.validate(initialvalues, { abortearly: false }); seterrors({}); } catch (error) { // if the form is invalid, then the errors are set to the state const newerrors = error.inner.reduce((acc, cur) => { acc[cur.path] = cur.message; return acc; }, {}); seterrors(newerrors); } } // creating the handleformsubmit function to handle the form submission function handleformsubmit() { // validating the form values validatevalues().then(() => { // set message based on the form is valid or invalid. if (object.keys(errors).length === 0) { setmessage(form is valid); } else { setmessage(form is invalid); } }); } return ( // rendering the form <view style = {elementstyles.container}> {/* text inputs */} <textinput style = {elementstyles.input} placeholder = name value = {initialvalues.name} onchangetext = {(value) => handlechange(name, value)} /> {errors.name && <text style = {elementstyles.error}> {errors.name} </text>} <textinput style = {elementstyles.input} placeholder = email value = {initialvalues.email} onchangetext = {(value) => handlechange(email, value)} /> {errors.email && <text style= {elementstyles.error}> {errors.email} </text>} <textinput style = {elementstyles.input} placeholder = password value = {initialvalues.password} onchangetext = {(value) => handlechange(password, value)} securetextentry /> {errors.password && ( <text style = {elementstyles.error}> {errors.password} </text> )} {/* submit button */} <touchableopacity style = {elementstyles.button} onpress = {handleformsubmit}> <text style = {elementstyles.buttontext}> submit form </text> </touchableopacity> <text> {message} </text> </view> );};export default app;
输出
用户学会了使用 yup 和 react-native 来进行表单验证。开发人员可以使用像 yup 这样的库,而不是编写自定义表单验证代码,这使得代码更具可读性和简单性。
以上就是如何在 javascript 中的 react native 中安装 yup?的详细内容。