【问题标题】:Update state when input value doesn't match the pattern当输入值与模式不匹配时更新状态
【发布时间】:2022-02-10 00:55:45
【问题描述】:

当用户输入的值与模式不匹配时,我想更新状态“errorFlag”,如何才能验证输入值?

         const [errorFlag, setErrorFlag] = useState(false);
         <Input
              name='E-Mail-Address'
              type='email'
              pattern="^[a-zA-Z0-9._:$!%-]+@[a-zA-Z0-9.-]+.[a-zA-Z]$"
              errorMessage="* Invalid E-Mail-Address"
              onChange={setEmail1}
              error={email1 === ''}  
              required={true}     
          />

表单输入

import React from "react";

export interface InputProps {
  ....
 onChange?: (value: string) => void;
}

export class Input extends React.Component<InputProps, {
  value: string;
}> {
  constructor(props: InputProps) {
    super(props);
    this.state = { value: '' };
  }
  private onChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    this.setState({ value: event.target.value });
    this.props.onChange?.(event.target.value);
  }
  render() {
    return (
      <div key="form-name" className="formrow" style={{...this.props.style}}>
        <input 
          type={this.props.type??"text"} placeholder={' '} id={id} className="forminput" pattern={this.props.pattern} onChange={this.onChange} required={this.props.required}
          />
        <span id="formInput-errorspan" className="errorSpan">{this.props.errorMessage}</span>
      </div>
    );
  }
}

【问题讨论】:

    标签: javascript html reactjs typescript


    【解决方案1】:

    您可以使用checkValidity 方法简单地返回真或假。

    export default function App() {
    
      const [errorFlag, setErrorFlag] = useState(false);
      const [email, setEmail] = useState("");
      const onChange = (e) => {
        setErrorFlag(e.target.checkValidity());
        setEmail(e.target.value);
      };
    
      return (
        <div className="App">
          {errorFlag ? "Valid" : "Invalid"}
          <br />
          <Input
            name="E-Mail-Address"
            type="email"
            pattern="^[a-zA-Z0-9._:$!%-]+@[a-zA-Z0-9.-]+.[a-zA-Z]$"
            errorMessage="* Invalid E-Mail-Address"
            onChange={onChange}
            required={true}
          />
          {email}
        </div>
      );
    }
    

    输入

    ...
    private onChange = (event: React.ChangeEvent<HTMLInputElement>) => {
        this.setState({ value: event.target.value });
        this.props.onChange(event);
     }
     ...
    

    Demo

    【讨论】:

    • 感谢您的回答,但我在输入字段中键入任何内容后立即收到此错误“无法读取未定义的属性(读取'checkValidity')”
    • 这是因为您使用了自定义输入组件,而不是原生输入元素。
    • 你的方法onChange必须从输入返回原生事件,你能分享Input组件吗?
    • 我已经更新了我的问题,你能告诉我如何在这里使用'checkValidity'吗?
    • 试试this.props.onChange?.(event);而不是this.props.onChange?.(event.target.value);
    猜你喜欢
    • 2014-08-06
    • 2021-09-27
    • 1970-01-01
    • 2020-01-28
    • 2020-04-28
    • 2018-09-12
    • 2016-09-23
    • 2020-09-20
    • 1970-01-01
    相关资源
    最近更新 更多