公告:魔扣目录网为广大站长提供免费收录网站服务,提交前请做好本站友链:【 网站目录:https://www.morko.net 】, 免友链快审服务(50元/站),

点击这里在线咨询客服
新站提交
  • 网站:51998
  • 待审:31
  • 小程序:12
  • 文章:1030137
  • 会员:747

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?的详细内容,更多请关注www.92cms.cn其它相关文章!

分享到:
标签:javascript Native React 如何在 安装
用户无头像

网友整理

注册时间:

网站:5 个   小程序:0 个  文章:12 篇

  • 51998

    网站

  • 12

    小程序

  • 1030137

    文章

  • 747

    会员

赶快注册账号,推广您的网站吧!
最新入驻小程序

数独大挑战2018-06-03

数独一种数学游戏,玩家需要根据9

答题星2018-06-03

您可以通过答题星轻松地创建试卷

全阶人生考试2018-06-03

各种考试题,题库,初中,高中,大学四六

运动步数有氧达人2018-06-03

记录运动步数,积累氧气值。还可偷

每日养生app2018-06-03

每日养生,天天健康

体育训练成绩评定2018-06-03

通用课目体育训练成绩评定