如何在React Native中使用JavaScript安装Yup
Yup是一个我们可以在React Native应用中安装的NPM包。它用于验证存储在单个对象中的表单值。此外,我们可以使用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()方法根据模式中定义的规则验证值。这里,values是一个包含表单属性名称和值对的对象。
步骤
- 步骤1 - 首先,开发者需要从Yup中导入所需的内容。
-
步骤2 - 在App()组件中,使用Yup创建“userFormSchema”,该schema定义了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;
输出
用户学会了使用Yup与react-native进行表单验证。开发者可以使用Yup这样的库来代替编写自定义的表单验证代码,使代码更易读和简单。