简体   繁体   中英

How do I validate a single form field in CodeIgniter?

I have a form that has validation rules that are set in a config file. I want to validate this form field using AJAX so that when focus leaves a certain form field, that field is checked by CI's form validation class. I have a jQuery AJAX script that calls one of my controllers which I would like to have validate the form field. using the form_validation->run('group') method won't work for this because it checks everything in the form and will always return false. How can I validate a single form field in CodeIgniter?

For this you could use a custom jquery function like:

//When the focus leaves the desired input, do the check with JS or with CI
$('#the_input').focusout(function() {

  //check values here or send to php with ajax
  if($(this).val == ''){  //I.E check if is blank
     alert("Blank!");
     return false;
  }

  //Or 'asking' to CI
  var url = "/path/to/codeigniter/function";
  $.get(url,function(data){
     if(data == true){
        alert("OK!");
     }
  });
});

If you wish, you could do this as a function returning true or false (instead of onMouseFocus), and call from your proper CI validation flow, like:

isInputXvalid(input){ //... return isValid; }

Hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM