【问题标题】:how to clear input onchange validation message -ReactHooks如何清除输入 onchange 验证消息 -ReactHooks
【发布时间】:2021-07-03 20:15:24
【问题描述】:

我想在验证满足或字段为空后清除输入验证消息

我有 2 个输入必须验证数字 onchange 本身。我正在使用反应挂钩

onchange 字段的代码(我们可以格式化这 1 个 onchange)

 const onChangePhNum = React.useCallback(
(value: string) => {
  const FormattedValue1 =   onlynumberFormatter(value)
  props.setphoneNumber(FormattedValue1)
   /*clearMessage() */either any one of the message will be displayed
  if (FormattedValue1 === '' || FormattedValue1?.length < 15) {
    setShowValidationMessage(true)
    setMessage(
      person.path,
      "invalidPhoneNumber: length must be 10 digit",
    )
  }
},
[showValidationMessage, props.phoneNumber],
)

const onChangezipCode = React.useCallback(
(value: string) => {
  const FormattedValue2 = noSpecialCharacters(value)
  props.setzipcode(FormattedValue2)
   /*clearMessage() */either any one of the message will be displayed
  if (FormattedValue2 === '' || FormattedValue2.length < 4) {
    setShowValidationMessage(true)
    setMessage(
      person.path,
      "invalidzipcode:zipcode must be 4 digit",
    )
  }
},
[showValidationMessage, props.zipCode],
)

我也有一个 clearMessage 方法,但对何时调用它感到困惑

   const clearMessage = React.useCallback((message) => {
if (showValidationMessage) {
  clearMessages(
    person.path,
    message,
  )
  setShowValidationMessage(false)
}
}, [showValidationMessage])

【问题讨论】:

    标签: reactjs react-hooks react-hook-form


    【解决方案1】:
    1. 验证的结果必须清楚地了解您是否有任何验证问题或一切都清楚。所以它进入状态。
    2. 必须实现验证消息条件呈现。

    去掉所有多余的东西,基本情况如下:

    const Component = () => {
      const [inputValue, setInputValue] = useState("")
      const [validationError, setValidationError] = useState("")
      
      function validate(string) {
        // some validation rules:
        if (string.length < 5) {
          return "Value must contain at least 5 symbols"
        }
        // basic return:
        return ""
      }
      
      function handleInputChange({target}) {
        setValidationError(validate(target.value))
        setInputValue(target.value)
      }
      
      return (
        <>
          <input value={inputValue} onChange={handleInputChange} />
          {validationError && <span>{validationError}</span>}
        </>
      )
    }
    

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-12
      • 1970-01-01
      相关资源
      最近更新 更多