如何在 JavaScript 中的 React Native 中安装 yup?

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?的详细内容,更多请关注双恒网络其它相关文章!

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需!
7. 如遇到加密压缩包,请使用WINRAR解压,如遇到无法解压的请联系管理员!
8. 精力有限,不少源码未能详细测试(解密),不能分辨部分源码是病毒还是误报,所以没有进行任何修改,大家使用前请进行甄别
9.本站默认解压密码为:www.sudo1.com
本站提供的一切软件、教程和内容信息仅限用于学习和研究目的。
不得将上述内容用于商业或者非法用途,否则,一切后果请用户自负。
本站信息来自网络收集整理,版权争议与本站无关。您必须在下载后的24个小时之内,从您的电脑或手机中彻底删除上述内容。
如果您喜欢该程序和内容,请支持正版,购买注册,得到更好的正版服务。
我们非常重视版权问题,如有侵权请邮件与我们联系处理。敬请谅解!

云资源网 » 如何在 JavaScript 中的 React Native 中安装 yup?

常见问题FAQ

免费下载或者VIP会员专享资源能否直接商用?
本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。更多说明请参考 VIP介绍。
提示下载完但解压或打开不了?
最常见的情况是下载不完整: 可对比下载完压缩包的与网盘上的容量,若小于网盘提示的容量则是这个原因。这是浏览器下载的bug,建议用百度网盘软件或迅雷下载。 若排除这种情况,可在对应资源底部留言,或 联络我们.。
你们有qq群吗怎么加入?
当然有的,如果你是帝国cms、易优cms、和pbootcms系统的爱好者你可以加入我们的QQ千人交流群https://www.sudo1.com/page-qun.html。
  • 会员数(个)
  • 12334资源数(个)
  •        
  • 资源(G)
  •        
  • 今日下载
  • 1406稳定运行(天)

提供最优质的资源集合

立即查看 了解详情