0

I'm building a simple donation app in ReactJS. Here is a working version here: https://stackblitz.com/edit/react-grzdgz

I've never done form error validation though. So if someone doesn't fill out a field, I'd like an error message to pop up, which says something like "this field must be completed".

I've been trying to follow this tutorial: https://learnetto.com/blog/how-to-do-simple-form-validation-in-reactjs

But I'm kinda getting lost, about how I can pass these functions/error messages, into my form, which sits in a seperate module. In the demo, everything sits in one file.

But in my app, my form sits seperately to index.js. So I link to it in index.js.

I'm almost there, I just need some help connecting everything up.

Can anyone help me get form error validation working?

The error handling functions all sit here: https://stackblitz.com/edit/react-grzdgz

The form itself sits here: https://stackblitz.com/edit/react-grzdgz?file=components%2FForm.js

And some form errror heres: https://stackblitz.com/edit/react-grzdgz?file=components%2FFormErrors.js

Any help would be great! Thank you!

1 Answer 1

1

On the submit, I would have a method called: validateFields, which would validate all field like you want (instead of using the default validator of html, which doesn't work on some browser). In the method, I would save all the field with an error.

If the error list (or object) is not empty, you use an alert or popup react-popup

If there are no error, you can call submit method.

Basically, it would look something like:

export default class DumbComponent extends React.Component {

  state = {} // all your field value

  validateField = () => {
    let error = []
    //Validate all your field

    if (error.length === 0) {
      this.submit()
    } else {
      this.showError() // You decide the way
    }
  }

  render() {
    return (
      <Form>
        <FieldOne />
        <Field2 />

        <SubmitButton onSubmit={this.validateField} />
      </Form>
    )
  }
}

Hope it answer your question!

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

2 Comments

Hi @alexandre rivest - thanks for the post. I don’t think this works with the way I’ve currently built my app though? Eg what is <field one/2>? And even though submit is in my form.js. Can I still use <submit etc> on my app.js. Are you able to make this work in my code?
<FieldOne /> can be a radio button, a text input, anything really. Unfortunately, I don't have much time to go in your code and fix it. Rapidly, i would say that you can do the validation in the props handleSubmit of your component form

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.