Running Form Validation Tests
Having initialized the validation rules, the next step is to run the form validation tests. The process of running form validation tests is carried out by the following line of code:
$result = $this->validation->run();
This single line of code invokes the run() method, which is part of the Trongate's Validation class.
Let's take a moment to clarify how this method works.
The Run Method
The run() method is central to Trongate's form validation process. It executes all the validation rules you've set and determines whether or not the submitted form data is valid.
public function run(?array $validation_array = null): ?bool
How It Works
When run() is invoked, Trongate will execute all of the form validation test that have been set. The only prerequisite is that the form validation rules must be configured according to Trongate’s specified protocol for setting validation rules.
What Gets Returned
The run() method can return one of the following values:
true
if all validation tests have been passed.false
if at least one validation test has failed.null
if there is an interruption in script execution, such as a failure in CSRF protection.
Basic Usage
Here's a simplified example of how run() could be used inside a controller file:
public function submit(): void {
$this->validation_helper->set_rules('name', 'required|max_length[23]');
$this->validation_helper->set_rules('age', 'required|greater_than[15]');
// Run validation tests
$result = $this->validation->run();
if ($result) {
// Form submission successful
echo 'Form submission successful!';
} else {
// Form submission error
echo validation_errors(); // Display validation errors.
}
}
By using the run() method, you can easily validate submitted form data. This approach helps maintain data integrity and improves the overall security of your Trongate application.
The run() method includes automatic Cross-Site Request Forgery (CSRF) protection checks before executing the validation rules. This mechanism enhances the security of your forms against CSRF attacks.
To ensure proper generation and validation of CSRF tokens, it is essential to use Trongate's form_close() function when closing your forms. This function not only appends the closing </form>
tag but also generates and includes a hidden CSRF token field.
In the next section, we'll focus on how to display form validation errors.