'Update state when input value doesn't match the pattern

I want to update the state "errorFlag" when the user entered values that doesn't match the pattern, how can this be done to validate the input value?

         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}     
          />

FormInput

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>
    );
  }
}


Solution 1:[1]

You can use checkValidity method simply return true or false.

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>
  );
}

Input

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

Demo

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1