Yup是一個(gè)NPM包,我們可以在react-native應(yīng)用程序中安裝。它用于驗(yàn)證存儲(chǔ)在單個(gè)對(duì)象中的表單值。此外,我們可以使用 Yup 將不同類(lèi)型的驗(yàn)證添加到不同的表單字段。
用戶(hù)可以在項(xiàng)目目錄中執(zhí)行以下命令來(lái)在React Native中安裝Yup。
npm i Yup
登錄后復(fù)制
如果用戶(hù)使用 Yarn,可以使用以下命令。
yarn i Yup
登錄后復(fù)制
語(yǔ)法
用戶(hù)可以按照以下語(yǔ)法在react-native應(yīng)用程序中使用Yup進(jìn)行表單驗(yàn)證。
const schema = Yup.object().shape({
key1: Yup.string().required("Required"),
});
await schema.validate(values);
登錄后復(fù)制
在上面的語(yǔ)法中,我們使用 Yup 創(chuàng)建了模式,并使用 validate() 方法根據(jù)模式中定義的規(guī)則來(lái)驗(yàn)證值。這里,值是一個(gè)包含表單屬性名稱(chēng)和值對(duì)的對(duì)象。
步驟
第 1 步 – 首先,開(kāi)發(fā)人員需要從 Yup 中導(dǎo)入所需的內(nèi)容。
步驟 2 – 在 App() 組件中,使用 Yup 創(chuàng)建一個(gè)“userFormSchema”,它定義了 Student_id、age 和 Portfolio 字段的規(guī)則。這里,student_id 是一個(gè)字符串和必填字段,age 是一個(gè)正整數(shù)和必填字段,portfolio 是網(wǎng)站的 URL。
第 3 步 – 現(xiàn)在,使用“useState”掛鉤定義學(xué)生信息和驗(yàn)證消息的狀態(tài)。
第4步 – 定義handleChange()函數(shù),該函數(shù)將鍵和值作為參數(shù),并更新“initialValue”狀態(tài)對(duì)象中的值。
第 5 步 – 接下來(lái),定義 validateValues() 函數(shù),該函數(shù)通過(guò)將 userFormSchema 作為引用、將 StudentInfo 對(duì)象作為參數(shù)來(lái)使用 validate() 方法來(lái)驗(yàn)證表單價(jià)值觀。
第 6 步 – 根據(jù)表單值的驗(yàn)證將消息設(shè)置為“消息”狀態(tài)。
示例 1
在下面的示例中,我們創(chuàng)建了一個(gè)表單來(lái)收集學(xué)生信息。我們添加了三個(gè)輸入字段來(lái)獲取 Student_id、年齡和作品集網(wǎng)站的 URL。此外,我們還創(chuàng)建了提交按鈕。
每當(dāng)用戶(hù)單擊提交按鈕時(shí),都會(huì)調(diào)用 validateValues() 函數(shù),該函數(shù)會(huì)在屏幕上顯示驗(yàn)證消息。
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;
登錄后復(fù)制
輸出
示例 2
下面的例子是上面例子的高級(jí)版本。在這里,我們有三個(gè)輸入字段,其中包含用戶(hù)名、電子郵件和密碼。
此外,我們還使用 Yup 創(chuàng)建了 userFormSchema 來(lái)驗(yàn)證表單。在這里,我們定義了規(guī)則,因此名稱(chēng)的長(zhǎng)度應(yīng)至少為三個(gè)字符,并且始終是必需的。電子郵件應(yīng)遵循格式并始終為必填項(xiàng),密碼長(zhǎng)度應(yīng)至少為六個(gè)字符。
此外,我們還為輸入字段和錯(cuò)誤消息提供了一些樣式。當(dāng)用戶(hù)單擊提交按鈕時(shí),它會(huì)調(diào)用handleFormSubmit()函數(shù),該函數(shù)通過(guò)調(diào)用validateValues()函數(shù)來(lái)獲取驗(yàn)證結(jié)果。它顯示基于表單驗(yàn)證的輸出消息。
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;
登錄后復(fù)制
輸出
用戶(hù)學(xué)會(huì)了使用 Yup 和 React-Native 來(lái)進(jìn)行表單驗(yàn)證。開(kāi)發(fā)人員可以使用像 Yup 這樣的庫(kù),而不是編寫(xiě)自定義表單驗(yàn)證代碼,這使得代碼更具可讀性和簡(jiǎn)單性。
以上就是如何在 JavaScript 中的 React Native 中安裝 yup?的詳細(xì)內(nèi)容,更多請(qǐng)關(guān)注www.92cms.cn其它相關(guān)文章!






