[英]Validate string against allowed values / array of strings
在Yup
中,是否有任何內置檢查來根據允許值數組驗證字符串? 還是我必須為此編寫自己的測試 function ?
const fruit = 'apple';
const allowedFruits = ['orange', 'cherry'];
// I want to check if fruit is one of the allowedFruits. Fruit is coming from a text field / user input.
更新:我想強調這個問題是關於Yup
驗證庫的,而不是如何在普通的 JavaScript 中做到這一點。
const selectedFruit = "apple";
const allowedFruits = ['orange', 'cherry'];
const isInAllowedFruits = allowedFruits.some(fruit => fruit === selectedFruit)
只需使用 boolean isInAllowedFruits
。
嘗試使用:
const fruit = 'apple'; const fruit1 = 'orange'; const allowedFruits = ['orange', 'cherry']; console.log(allowedFruits.includes(fruit)); console.log(allowedFruits.includes(fruit1));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.