React中输入值不匹配正则模式时更新errorFlag状态的实现方案
errorFlag State When Input Doesn't Match Regex Pattern Got it, let's figure out how to update that errorFlag state when the email doesn't match your regex pattern. Here are a couple of straightforward approaches you can take, based on your existing code setup:
Approach 1: Validate Directly in the Parent Component's onChange Handler
This is the quickest fix if you don't want to modify your custom Input component. You can reuse the regex pattern in your parent component's email update function to check validity and toggle errorFlag at the same time.
First, a quick note on your regex: The final . in your pattern isn't escaped, which means it will match any character instead of a literal dot. Update it to ^[a-zA-Z0-9._:$!%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]$ (notice the \. before the final domain part) to properly validate email domains.
Then modify your setEmail1 function in the parent component:
const setEmail1 = (value: string) => { // Update the email state first setEmail(value); // Define the corrected regex pattern const emailRegex = /^[a-zA-Z0-9._:$!%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]$/; // Update errorFlag: set to true if the value doesn't match the regex setErrorFlag(!emailRegex.test(value)); };
Adjust the error prop on your Input to account for both empty input and invalid format:
<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 === '' || errorFlag} // Combine empty check and invalid format check required={true} />
Approach 2: Extend the Custom Input Component to Pass Validation Status
This is a cleaner, more scalable approach—your Input component handles the validation logic and tells the parent component whether the input is valid, so you don't have to duplicate the regex pattern.
Step 1: Update the InputProps Interface
Add a new callback prop to notify the parent about validation changes:
export interface InputProps { // ... your existing props onValidationChange?: (isValid: boolean) => void; }
Step 2: Modify the Input Component's onChange Method
Use the native checkValidity() method on the input element to validate against the pattern and required props, then trigger the callback:
private onChange = (event: React.ChangeEvent<HTMLInputElement>) => { const value = event.target.value; this.setState({ value }); this.props.onChange?.(value); // Check if the input is valid using HTML5's built-in validation const isValid = event.target.checkValidity(); // Send the validation result to the parent component this.props.onValidationChange?.(isValid); };
Step 3: Use the New Prop in the Parent Component
Now you can update errorFlag directly when the validation status changes:
<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} onValidationChange={(isValid) => setErrorFlag(!isValid)} // Update errorFlag here error={email1 === '' || errorFlag} required={true} />
Bonus: Validate on Form Submission
Don't forget to recheck validity when the user submits the form (in case they skipped typing and hit submit directly):
const handleSubmit = () => { // Option 1: Reuse the regex check (for Approach 1) const emailRegex = /^[a-zA-Z0-9._:$!%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]$/; const isValid = emailRegex.test(email1) && email1 !== ''; setErrorFlag(!isValid); if (isValid) { // Proceed with form submission console.log("Email is valid, submit form!"); } };
If you used Approach 2, you can also use a ref to access the input element and validate it directly (you'll need to update your Input component to accept a ref using React.forwardRef):
import { useRef } from 'react'; // In your parent component const emailInputRef = useRef<HTMLInputElement>(null); const handleSubmit = () => { if (emailInputRef.current) { const isValid = emailInputRef.current.checkValidity(); setErrorFlag(!isValid); if (isValid) { // Proceed with submission } } }; // Update your Input component to accept the ref export const Input = React.forwardRef<HTMLInputElement, InputProps>((props, ref) => { return ( <div className="formrow" style={{...props.style}}> <input ref={ref} type={props.type ?? "text"} placeholder={' '} id={props.name} className="forminput" pattern={props.pattern} onChange={props.onChange} required={props.required} /> <span className="errorSpan">{props.errorMessage}</span> </div> ); }); // Pass the ref to your Input <Input ref={emailInputRef} // ... other props />
内容的提问来源于stack exchange,提问作者New at Leaflet

