redux-form-material-ui icon indicating copy to clipboard operation
redux-form-material-ui copied to clipboard

Checkbox field validation

Open Duskfall opened this issue 7 years ago • 1 comments

Lets say we have the example with the checkbox:

<Field name="agreeToTerms" component={Checkbox} label="Agree to terms?" validate={[required]}/>

The validation doesn't work because there isn't a mapError function in checkbox component. Is that on purpose? This is for version 5.0

Duskfall avatar Jun 04 '18 10:06 Duskfall

My version in the end is:

const CheckboxWithLabelAndError = ({
                     input,
                     label,
                     classes,
                     meta: {touched, error},
                     children,
                     ...custom
                   }) => (
  <FormControl error={Boolean(touched && error)} fullWidth>
    <FormControlLabel
      label={label}
      control={
        <Checkbox
          {...input}
          onChange={event => input.onChange(event.target.checked)}
          value={input.value}
          checked={input.value}
          {...custom}>
          {children}
        </Checkbox>
      }
    />
    {touched && error && <FormHelperText className={classes.checkboxError}>{error}</FormHelperText>}
  </FormControl>
);

Example:

<Field
      color="primary"
      name="agreeToTerms"
      className={classes.checkbox}
      classes={{checked: classes.checked, checkboxError: classes.checkboxAgreeError}}
      label="test label which is passed to checkbox"
      component={CheckboxWithLabelAndError}
      validate={[required]}
/>

This way we get inline validation errors for Checkbox component as well

Duskfall avatar Jun 04 '18 11:06 Duskfall