question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

When I click the submit button, how do I trigger the error returned by the backend API to be displayed in the error message?

See original GitHub issue
//处理提交(字段有效或无效都会执行)
  handleSubmit(event, errors, values) {
    //console.log(event, errors, values);
  }

  //后端交互并返回错误信息
  validate(value, ctx, input, cb){
    cb('123');
  }
...
<AvForm
                      className="av-tooltip"
                      onSubmit={this.handleSubmit}
                    >
                      <AvField name="username" label="手机号 / 邮箱" type="text" errorMessage={this.props.user.errors[0]} validate={{async: this.validate}} />

                      <AvField name="password" label="密码" type="text" errorMessage={this.props.user.errors[0]} validate={{async: this.validate}} />
                      <div className="row">
                        <div className="col-sm-8">
                          <AvField name="captcha_code" label="验证码" type="text" errorMessage={this.props.user.errors[0]} validate={{async: this.validate}} />
                        </div>
                        <div className="col-sm-4">
                          <img
                            src={ this.props.user.captcha_image }
                            onClick={ () => this.props.reCaptcha() }
                            style={{cursor:'pointer'}}
                          />
                        </div>
                      </div>
                      <div className="d-flex justify-content-between align-items-center">
                        <NavLink to={`/forgot-password`}>
                          忘记密码?
                        </NavLink>
                        <Button
                          color="primary"
                          className="btn-shadow"
                          size="lg"
                        >
                          登录
                        </Button>
                      </div>
                    </AvForm>

How do I trigger an error returned by the backend API to display in the error message when I click the Submit button? Instead of triggering an API request when the input box loses focus. Because my verification code has been deleted when the request is successful, click the button verification code error

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:6

github_iconTop GitHub Comments

1reaction
sgruenholz11commented, Mar 4, 2020

I’m a little late to the party here, but hope this helps someone:

I had the same problem. In my server response (after submitting the form) I’m passing back a list of error messages and saving them to local state. Similar to @noecs I set up a custom validation rule to check if an error message exists for a field in local state.

The missing piece was I needed a way to force trigger the form fields to run validation again AFTER I get the response back from the server.

You can do this with by creating a ref on the form. this.form = React.createRef();

Then in your response callback you can trigger a revalidation and update using this.form.current.validateAll(values, true);

Example:

class ServerValidationExample extends Component {
    constructor(props) {
        super(props);

        this.state = {
            values: {},
            errors: [],
            serverErrors: {},
        };

        this.form = React.createRef();
        this.handleValidSubmit = this.handleValidSubmit.bind(this);
        this.handleInvalidSubmit = this.handleInvalidSubmit.bind(this);
        this.handleServerSubmit = this.handleServerSubmit.bind(this);
        this.serverValidate = this.serverValidate.bind(this);
    }


    handleInvalidSubmit(event, errors, values) {
        this.setState({ errors, values });
    }

    handleValidSubmit(event, values) {
        this.setState({ values });

        // client-side validation passed, 
        // OK to make server request
        this.handleServerSubmit();
    }

    handleServerSubmit() {
        const { values } = this.state;

        somePromiseBasedRequest().then(
            response => {
                // where the server response data contains
                // success: bool, 
                // message: string, 
                // errors: obj like { 'name': 'No nicknames!' }

                const { success, message, errors } = response.data;

                if (success) {
                    // success case, do whatever...

                    this.setState({ serverErrors: {} });

                } else {
                    // failure case.

                    // set serverErrors state, then force
                    // all the form fields to re-validate to update the UI.
                    this.setState({ serverErrors: errors }, () => {
                        if (this.form.current) {
                            this.form.current.validateAll(values, true);
                        }
                    });
                }
            }
        );
    }

    // special validation rule to check against any
    // serverErrors that may exist for this field.
    serverValidate(value, context, input, callback) {
        let serverError = this.state.serverErrors[input.props.name];
        if (typeof serverError == "undefined") serverError = true;
        callback(serverError);
    }

    render() {
        return (
            <AvForm
                onValidSubmit={this.handleValidSubmit}
                onInvalidSubmit={this.handleInvalidSubmit}
                ref={this.form}
            >
                <AvField
                    label="What is your name?"
                    name="name"
                    type="text"
                    validate={{
                        required: {
                            value: true,
                            errorMessage: "Please enter your name"
                        },
                        server: this.serverValidate
                    }}
                />
                <Button color="primary">Submit</Button>
            </AvForm>
        );
    }
}
0reactions
noecscommented, Dec 3, 2018

Oh, my god. I just went to the documentation of the reactstrap and found that it was so simple. The original want to trigger an error is the mechanism of reactstarp. Just give the invalid parameter to the avinput component, boolean

Read more comments on GitHub >

github_iconTop Results From Across the Web

Whether all error messages should come from the backend in ...
So my backend developer sends me error messages that are not suitable for output to an alert arguing that the message is I...
Read more >
Express Tutorial Part 6: Working with forms - MDN Web Docs
The submit input will be displayed as a button (by default)—this can ... Error messages can be returned in an array using `errors.array()`....
Read more >
503 Service Unavailable - Backend Server | Apigee Edge
In Apigee Edge, the 503 Service Unavailable Error can be returned from a backend server under either of the following circumstances:.
Read more >
How Does the Frontend Communicate with the Backend?
Requests are being made, but the browser does that in the background. It doesn't reload the whole page. That's AJAX. Javascript can be...
Read more >
Data Validation – How to Check User Input on HTML Forms ...
Here, the form made a call to its server side code, and returned a validation error after performing additional credit card checks.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found