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


Yup是一个NPM包,我们可以将其安装在React Native应用中。它用于验证存储在单个对象中的表单值。此外,我们可以使用Yup为不同的表单字段添加不同类型的验证。

用户可以在项目目录中执行以下命令来安装Yup到React Native。

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()方法根据模式中定义的规则验证值。这里,values是一个包含表单属性名称和值对的对象。

步骤

  • 步骤1 - 首先,开发者需要从Yup导入所需的内容。

  • 步骤2 - 在App()组件中,使用Yup创建一个'userFormSchema',它定义了student_id、age和portfolio字段的规则。这里,student_id是字符串且必填字段,age是正整数且必填字段,portfolio是网站的URL。

  • 步骤3 - 现在,使用'useState'钩子定义学生信息和验证消息的状态。

  • 步骤4 - 定义handleChange()函数,它以键和值作为参数,并在'initialValue'状态对象中更新值。

  • 步骤5 - 接下来,定义validateValues()函数,它使用validate()方法,以userFormSchema作为参考,并以studentInfo对象作为参数来验证表单值。

  • 步骤6 - 根据表单值的验证结果,将消息设置为'message'状态。

示例1

在下面的示例中,我们创建了一个表单来收集学生信息。我们添加了三个输入字段来获取学生的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;

输出

用户学习了如何在React Native中使用Yup进行表单验证。与编写自定义表单验证代码相比,开发者可以使用Yup等库,这使代码更易读且更简单。

更新于:2023年4月24日

4K+ 浏览量

启动你的职业生涯

完成课程获得认证

开始学习
广告