【问题标题】:How to show validation error in form in react js?如何在 React js 中以表单形式显示验证错误?
【发布时间】:2021-12-24 12:22:19
【问题描述】:

我创建了一个表单并将其连接到服务器。

 <form>
        <h2>Create Account</h2>

        <fieldset>
          <label for="name">Username</label>
          <input
            onChange={(e) => handle(e)}
            value={data.name}
            type="text"
            id="name"
            name="name"
          />

          <label for="email">Email</label>
          <input
            onChange={(e) => handle(e)}
            value={data.email}
            type="email"
            id="email"
            name="email"
          />

          <label for="password">Password</label>
          <input
            onChange={(e) => handle(e)}
            value={data.password}
            type="text"
            id="password"
            name="password"
          />
          <label for="confirmPassword">Confirm Password</label>
          <input
            onChange={(e) => handle(e)}
            value={data.confirmPassword}
            type="text"
            id="confirmPassword"
            name="confirmPassword"
          />
        </fieldset>
        <button type="submit" onClick={(e) => sendData(e)}>
          Create Account
        </button>
      </form>

如果验证错误响应是这样的 "message": "ValidationError: confirmPassword: 确认密码不匹配"

通过正则表达式,我可以从这条消息中找出错误,例如“确认密码不匹配”。

我不知道如何在相应的输入字段下方显示此错误?

【问题讨论】:

    标签: javascript html css reactjs forms


    【解决方案1】:
    1. 在 reducer 中,您应该创建验证函数
    const reducer = combineReducers({
      form: formReducer.validation({
        loginValidation: loginValidation,
      })
    })
    
    const loginValidation = values => {
      const errors = {}
      if (!values.email) {
        errors.email = 'Required'
      } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)) {
        errors.email = 'Invalid email address'
      }
    
      if (!values.password) {
        errors.age = 'Required'
      }
    
      if (!values.confirmPassword) {
        errors.age = 'Required'
      }
    
      if (values.confirmPassword !== values.password) {
        errors.age = 'Confirm Password did not match'
      } 
      return errors
    }
    
    1. 在表单组件中,你应该这样做
    <div>
      <label>Email</label>
      <Field name="email" component={email =>
         <div>
          <input type="text" {...email} placeholder="Email"/>
          {email.touched && email.error && <span>{email.error}</span>}
         </div>
        }/>
          </div>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-24
      • 2019-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多