我希望獲得有關我的 React Native App 驗證錯誤邏輯的幫助。
我的應用程式有 2 個輸入欄位。我希望用戶選擇開始日期和結束日期(日期格式 YYYY-MM-DD)(必須鍵入 DATE 以遵循設計約束)。單擊搜索按鈕后,我將使用日期范圍呼叫 api。
這是我為輸入 按鈕部分獲得的代碼:
const [startDate, setStartDate] = useState();
const [endDate, setEndDate] = useState();
return(
<TextInput
style={styles.inputDate}
placeholder='Start Date YYYY-MM-DD'
onChangeText={setStartDate}/>
<TextInput
style={styles.inputDate}
placeholder='End Date YYYY-MM-DD'
onChangeText={setEndDate}/>
<View style={styles.buttonSearch}>
<Button
title='Search'
onPress={searchDateRange} (calls the api) />
</View>
因此,我想確保用戶輸入的日期與字串長度為 10(例如 2021-01-01 )和包含數字和“-”的日期相匹配(試圖避免這種格式的日期 = 2021/01/ 01 因為它不適用于我的 api)
這是我迄今為止嘗試過但沒有成功的方法:
const [startDate, setStartDate] = useState();
const [endDate, setEndDate] = useState();
const submitSearch = () => {
if(setStartDate.length = 10 ){
searchDateRange(call api function)
}else{
Alert.alert('opss!', 'date must follow the YYYY-MM-DD format', [{text: 'ok'}])
}
}
return(
<TextInput
style={styles.inputDate}
placeholder='Start Date YYYY-MM-DD'
onChangeText={setStartDate}/>
<TextInput
style={styles.inputDate}
placeholder='End Date YYYY-MM-DD'
onChangeText={setEndDate}/>
<View style={styles.buttonSearch}>
<Button
title='Search'
onPress={submitSearch} />
</View>
我也試過這個:
const [startDate, setStartDate] = useState();
const [endDate, setEndDate] = useState();
const submitSearch = (text) => {
if(text.length = 10 ){
setStartDate(text)
searchDateRange(call api function)
}else{
Alert.alert('opss!', 'date must follow the YYYY-MM-DD format', [{text: 'ok'}])
}
}
return(
<TextInput
style={styles.inputDate}
placeholder='Start Date YYYY-MM-DD'
onChangeText={text => setStartDate(text)}/>
<TextInput
style={styles.inputDate}
placeholder='End Date YYYY-MM-DD'
onChangeText={setEndDate}/>
<View style={styles.buttonSearch}>
<Button
title='Search'
onPress={submitSearch} />
</View>
因此,最終目標是檢查兩個日期以確保它們匹配日期格式并呼叫 api。感謝大家的幫助!
uj5u.com熱心網友回復:
您可以使用正則運算式submitSearch驗證“YYYY-MM-DD”的日期格式。
const submitSearch = () => {
var date_regex = /^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/;
if(!date_regex.test(startDate)){
Alert.alert('opss!', 'Start date must follow the YYYY-MM-DD format', [{text: 'ok'}]);
return;
}
if(!date_regex.test(endDate)){
Alert.alert('opss!', 'End date must follow the YYYY-MM-DD format', [{text: 'ok'}]);
return;
}
//Call API function here
}
您可能會在此處的帖子中看到更多內容。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/513516.html
