Killzerman
Killzerman

Reputation: 323

Jquery validation for div

I've set up a page with a bunch of contenteditbale divs, along with some js/ajax functionality so that a user can inline edit.

<div class="inlineEdit" contenteditable="true"></div>

JS is a s such:

$(document).ready(function(){
$('div.inline-edit').blur(function()
{

    var pathArray = window.location.pathname.split( '/' );
    var segment_3 = pathArray[3];
    var editableObj = $(this);
    var token_input = $('input.token');
    var save_data ={};
    var token_name = token_input.attr('name');

    save_data['field'] = editableObj.attr('id');
    save_data['id'] = editableObj.closest('.inline-id').attr('id');
    save_data['editedValue'] = editableObj.text();

    $.ajax({
        url: segment_3+'/update',
        type: 'POST',
        data:save_data,
        success: function(){
        //on success functionality

        }        
   });
});

});

This part all works perfectly grand, all the right fields get updated with the right info. All i need is some way to validate that information before it get to the ajax

I know of JQuery Validation however I'm pretty sure it doesn't work with divs.

Is there a solution or am I stuck/have to change up the divs?

Upvotes: 1

Views: 94

Answers (1)

Roy
Roy

Reputation: 1977

You can create a temporary input box and pass the value through it to check validity. I wrote a function to use HTML5 validation to check for validity.

  function validityChecker(value, type) {
      type = type?type:'text'
      $('body').append('<input id="checkValidity" type="'+type+'" style="display:none;">');
      $('#checkValidity').val(value)
      validity = $('#checkValidity').val()?$('#checkValidity').val().length>0:false && $('#checkValidity')[0].checkValidity()
      $('#checkValidity').remove();
      return validity;
  }

In your case use like this:

if(validityChecker(save_data['editedValue'], 'number')){ // if you want to check for number
    $.ajax({
        url: segment_3+'/update',
        type: 'POST',
        data:save_data,
        success: function(){
        //on success functionality
        }        
    })
}

Demo:

function validityChecker(value, type) {
  type = type?type:'text'
  $('body').append('<input id="checkValidity" type="'+type+'" style="display:none;">');
  $('#checkValidity').val(value)
  validity = $('#checkValidity').val()?$('#checkValidity').val().length>0:false && $('#checkValidity')[0].checkValidity()
  $('#checkValidity').remove();
  return validity;
}

save_data = 'This is not a number';
alert(validityChecker(save_data, 'number')) // false
alert(validityChecker(save_data, 'text')) // true
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 1

Related Questions