NewOldMax / react-form-validator-core

Core validator component for react forms
MIT License
94 stars 44 forks source link

Uncaught TypeError: _this.props.validatorListener is not a function #69

Closed coolbeatz71 closed 4 years ago

coolbeatz71 commented 4 years ago

I am implementing form validation inside my material-ui TextField as follow:

TextInput component

class TextInput extends ValidatorComponent {
  /**
   * render the component
   * @returns {object} JSX
   */
  render() {
    const {
      variant,
      id,
      label,
      autoFocus,
      multiline,
      rows,
      error,
      errorMessages,
      validators,
      requiredError,
      helperText,
      withRequiredValidator,
      ...rest
    } = this.props;

    const { isValid } = this.state;

    return (
      <TextField
        {...rest}
        fullWidth
        margin="normal"
        variant={variant}
        id={id}
        name={id}
        label={label}
        autoFocus={autoFocus}
        multiline={multiline}
        rows={rows}
        error={!isValid || error}
        helperText={(!isValid && this.getErrorMessage()) || helperText}
      />
    );
  }
}

TextInput.propTypes = {
  id: PropTypes.string.isRequired,
  label: PropTypes.string.isRequired,
  error: PropTypes.bool,
  helperText: PropTypes.string,
  variant: PropTypes.string,
  autoFocus: PropTypes.bool,
  multiline: PropTypes.bool,
  rows: PropTypes.string,
};

TextInput.defaultProps = {
  error: false,
  helperText: undefined,
  variant: 'outlined',
  autoFocus: false,
  multiline: false,
  rows: '8',
};

export default TextInput;

My Form

<ValidatorForm
 className={classes.form}
  autoComplete="off"
  noValidate
  onSubmit={this.handleSubmit}
>
  <TextInput
    id="email"
    label="Email"
    autoFocus={false}
    onChange={this.onChange}
    value={email}
    validators={['required', 'isEmail']}
    errorMessages={['this field is required', 'email is not valid']}
  />
  <Box marginTop={2}>
    <Button variant="contained" type="submit" className="button" fullWidth>
      send message
    </Button>
  </Box>
</ValidatorForm>

Problem

I don't understand why every time I enter a value on the TextField, I am getting this error:

Uncaught TypeError: _this.props.validatorListener is not a function

Would like to know the effective way of using this library alongside material-ui

NewOldMax commented 4 years ago

@coolbeatz71 hi you have redefined defaultProps of ValidatorComponent where was validatorListener: () => {} so you must add it to your defaultProps to fix the problem also you can use react-material-ui-form-validator library to work with material-ui forms