Home → GENERAL → Components → Default form and form validation
5.1. Default form and form validation
- What does this do?
- Under normal circumstances, this form will simply go to the destination page, via AJAX, and then load the response into that same <div>
- In order to take advantage of validation, but not utilize the "load response back into div" part, simply add the form attribute method="POST", this will tell the form that it should be submitted normally, i.e., not via AJAX
i. e.g., <form action="path/to/submit/page" method="POST">
- Using the Form
- First, ensure that the form in question is wrapped in a <div> with a class of ajax_form. The function will only affect forms wrapped within this <div>
- The function can be called by running bind_default_form()
- Validating the form
- The function that is responsible for validation is default_validation()
- Any field that is mandatory should have a class of js-required – this is applied to the <input>
- <input type="text"> that have js-required will only be validated in one dimension, i.e., whether or not the field is blank. If the field is blank, the user is alerted and the form submission is cancelled.
- If validation is required in more than one dimension, validating an email address for example, we have special classes that can be used. The values of these fields will be tested again a Regular Expression and will return an error if they failed the test.
i. js-email
ii. js-phone
- To validate <input type="radio"> just make sure that at least one of the radios from the group – i.e., that have the same name – have the class js-required
- To validate <input type="checkbox"> all the associated checkboxes must be wrapped in a <div> with a class of js-checkbox and js-required.
- In order to pass a custom validation, on the <form> in question, add the following:
i. <input type="hidden" name="form_validation" value="{{name_of_function_to_be_called}}">
ii. This function can itself contain a call to default_validation()[1], so there is no need to reinvent the wheel when customizing a validation
- Alerting the user[2]
- If the form has been found to be invalid, two things will happen:
i. The first error – aka the first invalid field – will be "focused"
ii. An alert with a given message will be displayed
[1] Developer note: default_validation() will return a Boolean value that can then be used to test against.
[2] Nothing has to be done in order for this to work