是的,基于其他字段值的多条件验证

问题描述

当“性别”字段值为其他或女性时,我必须验证“描述”字段,但当它是男性时,“描述”字段不需要验证。

首先我想展示这段代码,这是有效且有效的:

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css" rel="stylesheet"/>

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

<footer class="footer bg-dark ">
    <div class="container-fluid flex lead py-1">
       <div class="Box flex-basis-3">
           <h1>About</h1>
           <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Corporis voluptatum vel praesentium molestias consectetur ea consequuntur a quidem vitae iste?</p>
       </div> 
       <div class="Box flex-basis-3 text-center">
        <h1>CarolandHousing</h1>
        <p>copyright &copy; 2021</p>
        </div>
        <div class="Box flex-basis-3 text-right">
            <div class="display: flex; justify-content: flex-end">
               <span><a href="index.html">Home</a></span>
               <span><a href="features.html">Features</a></span>
               <span><a href="docs.html">Docs</a></span>
            </div>
            <div>
              <a href="#"><i class="fab fa-facebook fa-2x"></i></a>
              <a href="#"><i class="fab fa-instagram fa-2x"></i></a>
            </div>
        </div>
     </div>
</footer>

但现在我必须使用多个这样的条件:

description: Yup.string().when(['gender'],{
 is: (gender) => gender=== 'others',then: Yup.string().required('Description is required')
})

但是它不起作用。请给我一个解决方案。提前致谢...

解决方法

首先评估相等操作。

is: (gender) => gender === 'others' || 'female',// Not good

变成:

is: (gender) => (Boolean) || 'female',

如果 <Boolean>true,您将得到 true 作为结果,
如果 <Boolean>false,您将得到 "female" 作为结果。

解决方案:
相反,使用 /^(others|female)$/.test(gender)
或@evolution 建议的 ['others','female'].includes(gender)

is: (gender) => /^(others|female)$/.test(gender),

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test

或者如果你想让它长而明确:

is: (gender) => gender === "others" || gender === "female",

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...