No Special Characters

Prevent Special Characters

by Shawn Wood

HTML

<p>
This code prevents some special characters from being added to a field.
</p>
<input type="text" id="specialInput" placeholder="No Special Characters" />
<p>
The following special characters to block.
</p>
<p>
&Atilde;&cent;&Acirc;&iquest;&Acirc;&cent;
</p>
<textarea id="specialTextarea" class="tooltip" wrap="hard" rows="4" cols="60" spellcheck="false" placeholder="No Special Characters"></textarea>
<p>
Allows the special Characters to input
</p>
<input type="text" id="unspecialInput" placeholder="Allow Special Characters" class="allowSpecialChar" />
<p>
Allows the special Characters to textarea
</p>
<textarea id="unspecialTextarea" wrap="hard" rows="4" cols="60" spellcheck="false" placeholder="Allow Special Characters" class="tooltip allowSpecialChar"></textarea>
<form id="sampleClean">
<textarea id="clearTextarea" wrap="hard" rows="4" cols="60" spellcheck="false" placeholder="Clean Special Characters" class="tooltip">I have some special characters that need to be removed. They are right here: "â¿". Please remove them.</textarea>
<button id="cleanBtn" type="button">
Clear Special Chracters
</button>
</form>

JavaScript

function removeBadChar(string) {
  if (typeof string === 'string') {
    var NewString = string.replace(/[^\u0000-\u007E]/g, '');
    return NewString;
  } else {
    console.error('You can only remove special characters from a string.');
  }

}

var decodeEntities = (function() {
  // this prevents any overhead from creating the object each time
  var element = document.createElement('div');

  function decodeHTMLEntities (str) {
    if(str && typeof str === 'string') {
      // strip script/html tags
      str = str.replace(/<script[^>]*>([\S\s]*?)<\/script>/gmi, '');
      str = str.replace(/<\/?\w(?:[^"'>]|"[^"]*"|'[^']*')*>/gmi, '');
      element.innerHTML = str;
      str = element.textContent;
      element.textContent = '';
    }

    return str;
  }

  return decodeHTMLEntities;
})();



function noSpecialChar(event) {
  //
  //var regex = new RegExp("^[ A-Za-z0-9_@./#&+-\.%*!$]*$");
  //var regex = new RegExp("([A-Z])\w+");
  var regex = new RegExp("^[\n-~]*$"); // Expression allows 0-9, A-Z (upper and lower) and special characters on US Keyboard.
  var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
  if (!regex.test(key)) {
    event.preventDefault();
    return false;
  }
}

$(document).ready(function() {
  $('body').on('change blur input keypress paste', 'input[type="text"]:not(.allowSpecialChar), textarea:not(.allowSpecialChar)', function(event) {
    return noSpecialChar(event);
  });
  $('#cleanBtn').on('click', function(event) {
    var initialValue = $('#clearTextarea').val();
    var cleanedValue = removeBadChar(initialValue);
    $('#clearTextarea').val(cleanedValue);
  });
  console.log(decodeEntities('&Atilde;&cent;&Acirc;&iquest;&Acirc;&cent;'));
  console.log(decodeEntities('â¿¢'));
});