繁体   English   中英

如何在反应中验证两个输入字段?

[英]How to validate two input fields in react?

编辑 2:我通过将所有答案保存在一个数组中并使用includes来解决这个问题。 无论如何感谢所有帮助过的人

我在验证两个输入字段时遇到了困难。 如果只是一个,我觉得会简单很多,但是这里有两个字段。

<form onSubmit={handleSubmit}>
         <TextField
           label="Type (Cat/Dog/Fish)"
           variant="outlined"
           color='error'
           onChange={e => setUserInputPet(e.target.value)}
           value={userInputPet}
         />
         {showPetError && <Typography color='error'>Please enter Cat, Dog, or Fish</Typography>}

         <TextField
           label="Gender (Male/Female)"
           variant="outlined"
           color='error'
           onChange={e => setUserInputGender(e.target.value)}
           value={userInputGender}
         />
         {showGenderError && <Typography color='error'>Please enter Male or Female</Typography>}
</form>

也有用于条件渲染的简单状态

const [showPetError, setShowPetError] = useState(false)
const [showGenderError, setShowGenderError] = useState(false)

目前使用了这么多if statements ,但我针对的是非常具体的情况,它不好,而且会损害可读性,而且我知道必须有一种更有效的方法来做到这一点。

我要做的就是:第一个输入必须接受cat dogfish 否则,显示错误。 同样,第二个输入必须接受malefemale 否则,显示错误。

请帮忙,我觉得我把一个简单的问题复杂化了。 即使是这样的简单if statement似乎也不起作用:

if (userInputPet.toLowerCase() !== 'dog' || userInputPet.toLowerCase() !== 'cat' || userInputPet.toLowerCase() !== 'fish' ) {
  triggerPetError()
} 

我输入了狗/猫/鱼,它仍然显示错误

编辑:根据要求,下面是我的 if 语句。 抱歉,如果它很混乱/令人困惑,已经工作了很长时间。 顺便说一句,if 语句没有完成,它只是显示了我一直在做的事情

if (
      (userInputPet.toLowerCase() === 'cat') ||
      (userInputPet.toLowerCase() === 'dog') ||
      (userInputPet.toLowerCase() === 'fish')

      &&

      (userInputGender.toLowerCase() === 'male') ||
      (userInputGender.toLowerCase() === 'female')

    ) {

      console.log('success');

    } else if (
      (userInputPet.toLowerCase() === 'cat') ||
      (userInputPet.toLowerCase() === 'dog') ||
      (userInputPet.toLowerCase() === 'fish')

      &&

      (userInputGender.toLowerCase() !== 'male') ||
      (userInputGender.toLowerCase() !== 'female')      

    ) {
      triggerGenderError()
    }

您可以做的是,如果您已经有一组预定义的答案,您可以将其保存在 arrays 中。 然后,您只需检查数组中是否存在用户答案。

这是一个例子:

const typeArr = ['cat','dog','fish']
const genderArr = ['male', 'female']

假设您将用户输入值存储在状态中,请执行以下操作:

if(!typeArr.includes(userTypeInput.toLowerCase()){
   setShowPetError(true)
} else if (!genderArr.includes(userGenderInput.toLowercase())){
   setShowGenderError(true)
}else{
   //Do your thing
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM