How To Validate Contenteditable Based On Value

Contenteditable is a pretty new feature which allow you to transform any html element like div, td, th, p, span and so on in a textarea. You can use this feature in all major browsers and with few lines of jquery you can manipulate in any way the value from the div. Also you can send all data by ajax to server and save it to the database. In this tutorial we will try to validate the contenteditable text based on its value. 

Validate Contenteditable Based On Value

First of all let's create the element which will be used as content editable.

<div id="test" class="my_content_element" contenteditable="true">Test [Denzel Washington] ! Lorem Ipsum is  [Hollywood]. the printing and typesetting.</div>

 

To validate contenteditable elements you can use the following function which is called on keyup, keydown and paste.

jQuery(".my_content_element").on('click paste keydown keyup', function (e) {
  var text = jQuery(this).text();
  var fullID = text.match(/\[([^\]]+)]/g);
  
  if(fullID.length ==2){
    jQuery(this).css("color","black");
    console.log('All:' + text.length + '#Firstname:' + fullID[0].length + '#LocationName:' + fullID[1].length);
  if ((fullID[0].length >= 50 || fullID[1].length >= 60 || text.length >= 100) && (e.keyCode !== 46 && e.keyCode !== 8)){
    return false;
  }
  } else {
  console.log('Type the firstname and the LocationName between brackets [] ');
  jQuery(this).css("color","red");
  }
});

In this example we will validate the text which is added inside the brackets and we will check for Firstname and location name. Let us know if you need any help with this function.

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x