Search code examples
javascriptreactjsnewforms

react newforms, throw error on server response


I am using react newforms for react form handling. I find it really good but couldn't figure out how to trigger an error on a given input field if the server responses with an error.

For example you got a login form and you decide not to show an alert box under the form but throw a custom error that newforms catches and displays an error message Username does not exist right below the input field. (like it does on clientside validation)


Solution

  • You can use form.addError() for this:

    form.addError('username', 'Username does not exist.')
    

    If there isn't another state change happening associated with the server response, you may need to force your component to re-render.


    It also supports async validation, so it's possible to do the server call inside a custom validation method and get the form to add the error for you (suitability depends on when the server call needs to happen).

    http://newforms.readthedocs.org/en/latest/validation.html#asynchronous-validation