Welcome Guest, Not a member yet? Register   Sign In
Form Validation Individual Field Validation
#1

I think it would be a really good idea if you guys could add individual field validation to the form validation class.  This would make it extremely easy to use the class to validate forms through AJAX.  For example, when a user types in a username in a registration form and they focus away from that field, you could check for whether or not that name is in use with a function that individually validates form fields.

My idea for something like this would look something like this:


PHP Code:
<?php

class Register extends CI_Controller {

     public function index(){

         //the register form

   }

   public function checkfield($field){

      $this->load->library('form_validation');

      if(!$this->form_validation->check_field('group'$field)){

         echo show_error($field);

      }




Then the ajax call would use the URL of something like example.com/register/checkfield/username and the succeeding JS would look something like this:


PHP Code:
if(usernameResponse != ''){
 
     alert
("That username is already in use!");



What are your guys' thoughts on this?
Reply
#2

(This post was last modified: 04-01-2016, 02:21 AM by josepostiga.)

If you chain set_rules method with the run method you get exactly what you want.

PHP Code:
if (! $this->form_validation->set_rules($field$field'rules_here')->run()) {
    echo 
form_error($field);


Btw, I don't think this is related to CI4?...
Best regards,
José Postiga
Senior Backend Developer
Reply
#3

(This post was last modified: 04-01-2016, 11:06 PM by ShoeLace1291.)

(04-01-2016, 02:20 AM)josepostiga Wrote: If you chain set_rules method with the run method you get exactly what you want.

PHP Code:
if (! $this->form_validation->set_rules($field$field'rules_here')->run()) {
 
   echo form_error($field);


Btw, I don't think this is related to CI4?...


What if you set your validation rules in a config file?  I don't think that method would work if your rules are in a config file. And also, it relates to CI4 because I think they should rewrite the Form Validation class so that you can validate form fields individually based on rules set in a config file.
Reply
#4

(This post was last modified: 04-02-2016, 06:57 AM by josepostiga.)

It would work the same, as referenced here: https://codeigniter.com/user_guide/libra...rule-group

You'd just skip the set rules part and, in the config file, define the rule to use and then call that rule group specifically:

PHP Code:
if (! $this->form_validation->run('check_ajax_username')) {
    echo 
form_error('username');

Best regards,
José Postiga
Senior Backend Developer
Reply




Theme © iAndrew 2016 - Forum software by © MyBB