0

Is there any way to know that form is valid or not in react + material ui .I am using react material in my demo .I have three field in my form all are required . I want to check on submit button that form is valid or not

Here is my code https://codesandbox.io/s/w7w68vpjj7

I don't want to use any plugin

submitButtonHandler = () => {
    console.log("error");
    console.log(this.state.form);
  };

  render() {
    const { classes } = this.props,
      { form } = this.state;
    return (
      <div className={classes.searchUser__block}>
        <SearchForm
          handleInput={this.handleInputFieldChange}
          submitClick={this.submitButtonHandler}
          form={form}
        />
      </div>
    );
  }
1
  • Why don't you want to use any plugins? Eventually it will be easier to use one than not, if you have more forms or they get more complicated. Commented Sep 6, 2018 at 14:28

3 Answers 3

1

You would have to manually do that verification if you don't want to use any library. Material-ui does not have any validation built in as per their documentation. BUT it does give you some tools for that like errorMessage to text fields for example. You just have to play with it

Example:

class PhoneField extends Component
  constructor(props) {
    super(props)
    this.state = { errorText: '', value: props.value }
  }
  onChange(event) {
    if (event.target.value.match(phoneRegex)) {
      this.setState({ errorText: '' })
    } else {
      this.setState({ errorText: 'Invalid format: ###-###-####' })
    }
  }
  render() {
    return (
      <TextField hintText="Phone"
        floatingLabelText="Phone"
        name="phone"
        errorText= {this.state.errorText}
        onChange={this.onChange.bind(this)}
      />
    )
  }
}

a bit outdated example i had laying around

Sign up to request clarification or add additional context in comments.

Comments

1

Form validation can be pretty complex, so I'm pretty sure you'll end up using a library. As for now, to answer your question, we need to think about form submission flow. Here is a simple example:

  1. "Pre-submit"
    • Set isSubmitting to true
    • Proceed to "Validation"
  2. "Validation"

    • Run all field-level validations using validationRules
    • Are there any errors?
      1. Yes: Abort submission. Set errors, set isSubmitting to false
      2. No: Proceed to "Submission"
  3. "Submission"

    • Proceed with running your submission handler (i.e.onSubmit or handleSubmit)
    • Set isSubmitting to false

And some minimal implementation would be something like:

// ...imports
import validateForm from "../helpers/validateForm";
import styles from "./styles";
import validationRules from "./validationRules";

const propTypes = {
  onSubmit: PropTypes.func.isRequired,
  onSubmitError: PropTypes.func.isRequired,
  initialValues: PropTypes.shape({
    searchValue: PropTypes.string,
    circle: PropTypes.string,
    searchCriteria: PropTypes.string
  })
};

const defaultProps = {
  initialValues: {}
};

class SearchForm extends Component {
  constructor(props) {
    super(props);
    this.validateForm = validateForm.bind(this);
    this.state = {
      isSubmitting: false,
      values: {
        searchValue: props.initialValues.searchValue || "",
        circle: props.initialValues.circle || "",
        searchCriteria: props.initialValues.searchCriteria || ""
      },
      ...this.initialErrorState
    };
  }

  get hasErrors() {
    return !!(
      this.state.searchValueError ||
      this.state.circleError ||
      this.state.searchCriteriaError
    );
  }

  get initialErrorState() {
    return {
      searchValueError: null,
      circleError: null,
      searchCriteriaError: null
    };
  }

  handleBeforeSubmit = () => {
    this.validate(this.onValidationSuccess);
  };

  validate = (onSuccess = () => {}) => {
    this.clearErrors();
    this.validateForm(validationRules)
      .then(onSuccess)
      .catch(this.onValidationError);
  };

  onValidationSuccess = () => {
    this.setState({ isSubmitting: true });
    this.props
      .onSubmit(this.state.values)
      .catch(this.props.onSubmitError)
      .finally(() => this.setState({ isSubmitting: false }));
  };

  onValidationError = errors => {
    this.setState({ ...errors });
  };

  clearErrors = () => {
    this.setState({ ...this.initialErrorState });
  };

  updateFormValue = fieldName => event => {
    this.setState(
      {
        values: { ...this.state.values, [fieldName]: event.target.value }
      },
      () => this.validate()
    );
  };

  render() {
    // ...
  }
}

SearchForm.propTypes = propTypes;
SearchForm.defaultProps = defaultProps;

export default withStyles(styles)(SearchForm);

As you can see, if submission flow will grow larger (for example touching inputs, passing errors, etc), the of amount of complexity inside of a component will significantly grow as well. That is why it's more preferable to use a well-maintained library of choice. Formik is my personal preference at the moment.

Feel free to check out updated codesandbox. Hope it helps.

Comments

0

Hi Joy I've made desirable form validation if required fields are empty.

Here is the updated codesandbox: https://codesandbox.io/s/50kpk7ovz4

1 Comment

@Joy I have updated the condesandbox. Please verify the changes

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.