Home > Enterprise >  Validation for Input form component React
Validation for Input form component React

Time:08-11

I have a form component that include multiple TextFields and each one have different validation and error. Assume my TextField had custom validation prop that will take some conditions and show validation either onChange or onBlur for each TextField. I also have custom error prop that display message without condition.

const Address = ({
  onChange,
  required,
  error,
  value = {},
  validation = undefined,
}: AddressProps) => {

  const validator = {
    validationAddress: (value: string) => (value.length === 0) ?  'Address is required' : '',
    validationCity: (value: string) => (value.length === 0) ?  'City is required' : '',
  }
  const handleChange = (event) => {
    ...
  }

 return (
    <React.Fragment>
       <TextField
          id="address"
          label="address"
          type="text"
          required={required}
          onChange={handleChange}
          value={value.address}
          validationEvent="change"
          validation={validator.validationAddress}
        />
        <TextField
          id="city"
          label="city"
          type="text"
          required={required}
          onChange={handleChange}
          value={value.city}
          validationEvent="change"
          validation={validator.validationCity}
        />
     </React.Fragment>
export default Address;

After that I will implement my Address component in an App with submit button.

const App = () => {
   const handleSubmit = () => {
     ...
   }

   return (
     <Address />
     <button type='submit' onClick={handleSubmit}>
         Submit
     </button>
   )
}
export default App;

I saw many examples that input and form put together with submit button but I am struggling with handle them separately this way. My task is need to handle validation in Address component but have submit button as an optional option outside the Address component. My goal is validation message should not show until Submit button is clicked.

CodePudding user response:

Try this:

  1. move validator to parent component
  2. pass validatorMessage useState var to Address component
  3. call the validator by the click of submit button

Now the message is managed in the parent component and you control when the submit button displays it.

  • Related