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

王林
王林 转载
2023-09-13 11:53:07 252浏览

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;

输出

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

示例 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;

输出

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

用户学会了使用 Yup 和 React-Native 来进行表单验证。开发人员可以使用像 Yup 这样的库,而不是编写自定义表单验证代码,这使得代码更具可读性和简单性。

以上就是如何在 JavaScript 中的 React Native 中安装 yup?的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除