CodeIgniter Forums
Using the form validator with AJAX - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forumdisplay.php?fid=30)
+--- Thread: Using the form validator with AJAX (/showthread.php?tid=78471)



Using the form validator with AJAX - iampuping - 01-25-2021

I am submitting a form to my controller with AJAX, not via the action/method of the form itself. How do I use the validator with this method, since the data is coming in as a post request?


RE: Using the form validator with AJAX - Kohryu - 01-25-2021

If all elements are wrapped in form, you can use like this :

if(!$('#form-id')[0].checkValidity()){
document.querySelector('#form-id').reportValidity();
return false;
}


RE: Using the form validator with AJAX - harpreetsb - 02-02-2021

(01-25-2021, 09:15 PM)iampuping Wrote: I am submitting a form to my controller with AJAX, not via the action/method of the form itself. How do I use the validator with this method, since the data is coming in as a post request?

In your controller do something like this:
PHP Code:
$validationRules = array(
                'status' => [
                    'rules'  => 'required|alpha|in_list[active,deleted,disabled]',
                    'errors' => [
                        'required' => 'Your request is invalid',
                        'alpha'    => 'Your request is invalid'
                    ]
                ],
                'rec'    => [
                    'rules'  => 'required|numeric',
                    'errors' => [
                        'required' => 'Your request is invalid',
                        'numeric'  => 'Your request is invalid'
                    ]
                ]
            );

            /* if inputs dont validate */
            if ( ! $this->validate$validationRules ) )
            {
                /* return error */
                return $this->commonLib->sendJsonResponse(
                    400,
                    $this->validator->listErrors"error_template_name" // this is template file name, check validation documentation
                );
            }
            else
            {
                
// get values and save