Suman Islam
Suman Islam

Reputation: 13

onSubmit is not working in `react-material-ui-form-validator`

I am using react-material-ui-form-validator in my project. But onSubmit is not triggering when I submit the form. I tried a lot but couldn't solve the problem. I couldn't find why onSubmit don't work. Can Someone explain this?

State

constructor(props) {
    super(props);
    this.form = React.createRef();
    this.state = {
      open: false,
      currentColor: 'purple',
      newName: '',
      colors: [],
    };
  }

Validation Rule & handling events

componentDidMount() {
    const { colors, currentColor } = this.state;
    ValidatorForm.addValidationRule('isColorNameUnique', (value) => {
      colors.every(({ name }) => name.toLowerCase() !== value.toLowerCase());
    });
    // eslint-disable-next-line no-unused-vars
    ValidatorForm.addValidationRule('isColorUnique', (value) => {
      colors.every(({ color }) => color !== currentColor);
    });
  }

addNewColor = (event) => {
    event.preventDefault();
    const { currentColor, colors, newName } = this.state;
    const newColor = { color: currentColor, name: newName };
    this.setState({ colors: [...colors, newColor], newName: '' });
  };

  handleChange = (evt) => {
    this.setState({ newName: evt.target.value });
  };

Validator Form

          <ValidatorForm onSubmit={this.addNewColor} ref={this.form}>
            <TextValidator
              className={classes.textValidator}
              value={newName}
              placeholder="Color Name"
              variant="filled"
              margin="normal"
              onChange={this.handleChange}
              validators={['required', 'isColorNameUnique', 'isColorUnique']}
              errorMessages={[
                'this field is required',
                'Color name must be Unique',
                'Color already used',
              ]}
            />
            <Button
              className={classes.buttonCenter}
              type="submit"
              variant="contained"
              color="primary"
              style={{ backgroundColor: `${currentColor}` }}
            >
              Add Color
            </Button>
          </ValidatorForm>

Upvotes: 0

Views: 520

Answers (1)

Suman Islam
Suman Islam

Reputation: 13

I fixed the issue. Previously It didn't return any true or false value instead It returned undefined. Now code return either true or false

    componentDidMount() {
    ValidatorForm.addValidationRule('isColorNameUnique', (value) =>
      // eslint-disable-next-line react/destructuring-assignment
      this.state.colors.every(({ name }) => name.toLowerCase() !== value.toLowerCase())
    );

    ValidatorForm.addValidationRule('isColorUnique', () =>
      // eslint-disable-next-line react/destructuring-assignment
      this.state.colors.every(({ color }) => color !== this.state.currentColor)
    );
  }

Upvotes: 0

Related Questions