簡體   English   中英

根據允許的值/字符串數組驗證字符串

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM