It is necessary to handle server-side form validation errors. This is because the user needs to know the input field with the failed validation test and the input fields that passed.
Immediately you begin validation on the form fields, the library loops through your validation rules and executes the tests provided, then stores errors if any test fails.
To retrieve these errors, you would do something like this;
Make sure to invoke the getErrors()
method, only when the validate method returns false!
Now that we have retrieved the errors, we need to call a JavaScript function to help us display these errors to the end-user.
HELPER SCRIPT
There is a helper script attached to the library that contains the JavaScript functions needed to display these errors.
Navigate to the directory /frontend/helper.js
to
locate this helper script, then include the functions to your project.
The helper script contains 2 functions which are;
showErrors
Invoke this function and pass in the error object from the method
getErrors()
to insert errors to the form.
removeErrors
Invoke this function and pass in a formID to remove any error(s) inserted by the
showErrors
function.
In case you're using ...
AJAX
If you're using Ajax, within the error method, you need to call the
showErrors
function and pass in the error object for the function to insert errors
into the form, then within the success method, you need to call the
removeErrors
function and pass in the formID to remove any errors present in the
form.
Remember that not all failed http requests are to be treated as validation errors. You can set a response code to make your App understand that the failed request is a validation error.
PHP SCRIPT
If your form is submitted to the page itself, you can easily call the
showErrors
function and pass in the error object for the function to insert errors
into the form.
You don't need to call the removeErrors()
function if your form is submitted to the
page itself or to another PHP script, because the page will reload on every submit. However, it
is necessary that you call the function if you're using Ajax to process form submission.