Validate single field in modal form ajax codeigniter

0

I have a form in modal to enter data, and it validates me that the fields are empty before saving, but how do I validate that one of the fields is unique? that the information can not be repeated. It is done with codeigniter using modal, the code is this. The input is like this

             <div class="form-group">
                        <label class="control-label col-md-3">First Name</label>
                        <div class="col-md-9">
                            <input name="firstName" placeholder="First Name" class="form-control" type="text">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label col-md-3">Last Name</label>
                        <div class="col-md-9">
                            <input name="lastName" placeholder="Last Name" class="form-control" type="text">
                            <span class="help-block"></span>
                        </div>
                    </div>

...

function save()
{
$('#btnSave').text('saving...'); //change button text
$('#btnSave').attr('disabled',true); //set button disable 
var url;

if(save_method == 'add') {
    url = "<?php echo site_url('person/ajax_add')?>";
} else {
    url = "<?php echo site_url('person/ajax_update')?>";
}

// ajax adding data to database
$.ajax({
    url : url,
    type: "POST",
    data: $('#form').serialize(),
    dataType: "JSON",
    success: function(data)
    {

        if(data.status) //if success close modal and reload ajax table
        {
            $('#modal_form').modal('hide');
            reload_table();
        }
        else
        {
            for (var i = 0; i < data.inputerror.length; i++) 
            {
                $('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
                $('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]); //select span help-block class set text error string
            }
        }
        $('#btnSave').text('save'); //change button text
        $('#btnSave').attr('disabled',false); //set button enable 


    },
    error: function (jqXHR, textStatus, errorThrown)
    {
        alert('Error adding / update data');
        $('#btnSave').text('save'); //change button text
        $('#btnSave').attr('disabled',false); //set button enable 

    }
 });
}

and in the controller

  public function ajax_add()
  {
    $this->_validate();
    $data = array(
            'firstName' => $this->input->post('firstName'),
            'lastName' => $this->input->post('lastName'),
            'gender' => $this->input->post('gender'),
            'address' => $this->input->post('address'),
            'dob' => $this->input->post('dob'),
        );
    $insert = $this->person->save($data);
    echo json_encode(array("status" => TRUE));
  }

the one that validates the empty fields

  private function _validate()
{

    $data = array();
    $data['error_string'] = array();
    $data['inputerror'] = array();
    $data['status'] = TRUE;

    if($this->input->post('firstName') == '')
    {
        $data['inputerror'][] = 'firstName';
        $data['error_string'][] = 'First name is required';
        $data['status'] = FALSE;
    }

    if($this->input->post('lastName') == '')
    {
        $data['inputerror'][] = 'lastName';
        $data['error_string'][] = 'Last name is required';
        $data['status'] = FALSE;
    }

    if($this->input->post('dob') == '')
    {
        $data['inputerror'][] = 'dob';
        $data['error_string'][] = 'Date of Birth is required';
        $data['status'] = FALSE;
    }

    if($this->input->post('gender') == '')
    {
        $data['inputerror'][] = 'gender';
        $data['error_string'][] = 'Please select gender';
        $data['status'] = FALSE;
    }

    if($this->input->post('address') == '')
    {
        $data['inputerror'][] = 'address';
        $data['error_string'][] = 'Addess is required';
        $data['status'] = FALSE;
    }

    if($data['status'] === FALSE)
    {
        echo json_encode($data);
        exit();
    }
}

This is the part of the model that saves, deletes and updates

    public function get_by_id($id)
{
    $this->db->from($this->table);
    $this->db->where('id',$id);
    $query = $this->db->get();

    return $query->row();
}

public function save($data)
{
    $this->db->insert($this->table, $data);
    return $this->db->insert_id();
}

public function update($where, $data)
{
    $this->db->update($this->table, $data, $where);
    return $this->db->affected_rows();
}

public function delete_by_id($id)
{
    $this->db->where('id', $id);
    $this->db->delete($this->table);
}

get_by_id opts the id to edit the information.

    
asked by Francisco 31.12.2017 в 22:02
source

1 answer

1

You could validate it in the same input by losing the focus (blur). And when saving in your "save" function, check it.

$(document).on('blur','firstName', function(){
  $.ajax({
      type: "POST",
      // url con ruta a tu método o función en el controlador
      url: verify_firtsName,
      data: { 'firstName' : $(this).val() },
      success: function(msg){
        if (msg==1) { // duplicado
          $(this).addClass('invalido');
          alert("Tu Mensaje al usuario"); 
        } else{ // firtsName unico 
          $(this).removeClass('invalido');
        }   
      }
  });
});

The css class code (could be any other you like):

.invalido {
  border: 1px solid red;
}

The function or method in the codeigniter controller might look like this:

public function verify_firtsName() { 
    $valor = $this->input->post('firsName');
    $resultado = $this->tu_modelo->find_firtsName($valor);
    if($resultado) {
       echo 1;
    } else { 
       echo 0;
    }
}

The function in the model:

function find_firstName($valor) {
    $this->db->where('firtsName',$valor);
    return $this->db->get('tabladb')->result();
}

Inside the Save function you must validate the input simply by checking if the input has the "invalid" class defined. Or any other attribute that you want to indicate, you could even create a hidden input to control this but it would be more annoying.

To validate it according to this example, this code would suffice:

var obj = $("input[name=firtsName]");
if(obj.hasClass('invalido')) {
   alert('el nombre ya existe');
   return false;
}

If you detect the associated class then you stop the function.

I hope I have helped you or give you an idea of how you can solve it. Greetings!

    
answered by 07.01.2018 в 20:46