简体   繁体   English

ajax 表单提交上 Codeigniter 中的表单验证

[英]Form Validation in Codeigniter on ajax form Submission

I am new to codeigniter & javascript, I have been working with the form submission through ajax in codeigniter.我是 codeigniter 和 javascript 的新手,我一直在处理通过 ZAB664F63C186E473E15ZA 中的 ajax 提交的表单。 I need to use form validation on the text field & other inputs in the form.我需要对表单中的文本字段和其他输入使用表单验证。 I searched the web & couldn't find any resources or references.我搜索了 web 并找不到任何资源或参考资料。 Currently my form submission is working fine, I just need to validate my inputs using Jquery or ajax.目前我的表单提交工作正常,我只需要使用 Jquery 或 ajax 验证我的输入。

Here is my Model这是我的 Model

class test_model extends CI_Model {
    function save_data()
        {
            $name = $this->input->post('Name');
            $email = $this->input->post('Email');
            $contact = $this->input->post('Contact');
            $sex = $this->input->post('Sex');
            $country = $this->input->post('Country');   
            $data = array(
                'Name' => $name,
                'Email' => $email,
                'Contact' => $contact,
                'Sex' => $sex,
                'Country' => $country);
            $result = $this->db->insert('test2',$data);
            return $result;
        }
     }

My Controller just forwards the data to Model我的 Controller 只是将数据转发到 Model

class test extends CI_Controller {
    function __construct() {
        parent::__construct();
        $this->load->model('test_model');
        $this->load->helper('url');
    }
    function index() {
        $this->load->view('test_index');
    }       
    function save() { 
        $data = $this->test_model->save_data();
        echo json_encode($data);        
    }
}

Here is my View这是我的看法

<form>
    <div class="container" style="padding-top: 80px;">

        <div class="form-group">
            <label for="Name">First Name :</label>
            <div class="col-md-4">
                <input type="text" name="Name" id="Name" class="form-control" placeholder="Your Name..">
            </div>
        </div>

        <div class="form-group">
            <label for="Contact">Contact :</label>
            <div class="col-md-4">
                <input type="text" class="form-control" id="Contact" name="Contact" placeholder="Your Contact No..">
            </div>
        </div>

        <div class="form-group">
            <label for="Sex" class="col-md-1">Gender :</label>
            <div class="form-check form-check-inline">
                <label >
                <input type="radio" class="form-check-input" name="Sex" id="Sex" value="Male">Male  </label><span style="padding-right: 10px;"></span>

                <label>
                <input type="radio" class="form-check-input" name="Sex" id="Sex" value="Female">Female </label>
            </div>
        </div>

            <div class="form-group">
                <select class="form-control custom-select col-md-4" id="Country" name="Country">
                    <option value="">Select Country</option>
                    <option value="Europe">Europe</option>
                    <option value="United Stated of America">United States of America</option>
                    <option value="India">India</option>
                </select>
            </div>

        <div class="form-group">
            <button type="button" type="submit" id="btn_save" class="btn btn-primary" >
                <span class="spinner-border spinner-border-sm"></span>Create</button>
            <button type="button"  class="btn btn-secondary" >Close</button>
        </div>
    </div>
</form>

My JS code is below:我的JS代码如下:

$('#btn_save').on('click',function() {
                    var Name = $('#Name').val();
                    var Email = $('#Email').val();
                    var Contact = $('#Contact').val();
                    var Sex = $('input[name="Sex"]:checked').val();
                    var Country = $('#Country').find(":selected").val();
                    $.ajax({
                        type : "POST",
                        url : "https://localhost/newCrud/test/save",
                        dataType : "JSON",
                        data: {"Name":Name, "Email":Email, "Contact":Contact, "Sex":Sex, "Country":Country},
                        success : function (data) {
                            if(data == 1) {
                                $('[name = "Name"]').val("");
                                $('[name = "Email"]').val("");
                                $('[name = "Contact"]').val("");
                                $('[name = "Sex"]').val("");
                                $('[name = "Country"]').val();

                                alert("Data Inserted"); }
                        }
                    });
                    return false;
                });
        });

Guys, my above code works just fine, I need your help to know how can i validate my form using ajax, as it is already passing data to the model from here.伙计们,我上面的代码工作得很好,我需要你的帮助才能知道如何使用 ajax 验证我的表单,因为它已经从这里将数据传递给 model。 As far I've known that Codeigniter form_validate method can't be used in ajax form submission.据我所知,Codeigniter form_validate 方法不能用于 ajax 表单提交。 Really need your help guys.真的需要你们的帮助。 Thanks for your time & suggestions.感谢您的时间和建议。

Why not????为什么不????

You can use CI validation as it is a built in server side validation method and you are hitting your server through AJAX您可以使用CI 验证,因为它是一种内置的服务器端验证方法,并且您正在通过AJAX 访问您的服务器

You need to alter your code a bit你需要稍微改变你的代码

$.ajax({
    type : "POST",
    url : "https://localhost/newCrud/test/save",
    dataType : "JSON",
    data: {"Name":Name, "Email":Email, "Contact":Contact, "Sex":Sex, "Country":Country},
    success : function (data) {
        if(data == 1) {
            $('.form-group').removeClass('has-error');
            $('[name = "Name"]').val("");
            $('[name = "Email"]').val("");
            $('[name = "Contact"]').val("");
            $('[name = "Sex"]').val("");
            $('[name = "Country"]').val();

            alert("Data Inserted"); 
        }
    },
    error : function (error) {
      if(error.status == 500){
        var response = error.responseJSON.validation;
        $('.form-group').removeClass('has-error');
        $.each(response, function(index, item) {
            $('[name='+index+']').closest('.form-group').addClass('has-error');
        });
      }
    }

});

Update your controller as like this像这样更新您的 controller

public function save() { 
  // add this if not loaded earlier
  $this->load->library('form_validation');

  $this->form_validation->set_rules('Name','Name', 'required');
  $this->form_validation->set_rules('Contact','Contact', 'required');
  $this->form_validation->set_rules('Email','Email Address','required|valid_email');
  if ($this->form_validation->run() == FALSE) {
      $validation = $this->form_validation->error_array();
      return $this->output
              ->set_content_type('application/json')
              ->set_status_header(500)
              ->set_output( json_encode(array(
                  'validation' => $validation,
                  'message' => 'validation error !!!'
              )) );
  } 

  $data = $this->test_model->save_data();
  echo json_encode($data);        
}

Here i did validation for 3 fields name, email and contact.在这里,我对 3 个字段名称 email 和联系人进行了验证。 Also i used bootstrap error class 'has-error' to highlight failed elements.我还使用引导错误 class 'has-error' 来突出显示失败的元素。

Simply use the jQuery Validate plugin ( https://jqueryvalidation.org/ ).只需使用 jQuery 验证插件 ( https://jqueryvalidation.org/ )。

jQuery: jQuery:

$(document).ready(function () {

$('#myform').validate({ // initialize the plugin
    rules: {
        field1: {
            required: true,
            email: true
        },
        field2: {
            required: true,
            minlength: 5
        }
    }
});

});

HTML: HTML:

<form id="myform">
<input type="text" name="field1" />
<input type="text" name="field2" />
<input type="submit" />
</form>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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