Chars Directive jQuery Version

Avoid typing special characters with jQuery

by adnan lutfi

HTML

<label>Copy &amp; Paste to test
  <textarea readonly>12¡EÇ!%&/(3456"·$7H890'L)=?¿çLO^*;:`+,.-</textarea>
</label>
<label>Numbers only
  <input type="text" chars="0-9" placeholder="type or paste here" />
</label>

CSS

* {
  box-sizing: border-box;
}

body {
  font-family: "Lucida Sans Unicode", "Luxi Sans", sans-serif;
  font-size: 13px;
  color: #666;
  margin: 0;
  padding: 15px;
  background: #EBEBEB;
}

label {
  display: block;
  padding: 10px;
  background: #00ADA7;
  color: #FFF;
}

label + label {
  margin-top: 15px;
}

label input {
  border: 0;
  height: 20px;
  padding: 3px 5px;
  color: #666;
}

label textarea {
  display: block;
  border: 0;
  height: 30px;
  padding: 3px 5px;
  color: #666;
  width: 100%;
}

JavaScript

/*********************************************************
	- Author: Sebastian Cubillos
	- Github: @tianes
	- More Gists: https://gist.github.com/tianes/
	- Contact: [email protected]
	- Article: http://goo.gl/2sYxtp
**********************************************************/
$(document).on('keyup change input', '[chars]', function(event) {

  var $elem = $(this),
    value = $elem.val(),
    regReplace,
    preset = {
      'only-numbers': '0-9-',
      'numbers': '0-9\\s',
      'only-letters': 'A-Za-z',
      'letters': 'A-Za-z\\s',
      'email': '\\wÑñ@._\\-',
      'alpha-numeric': '\\w\\s',
      'latin-alpha-numeric': '\\w\\sÑñáéíóúüÁÉÍÓÚÜ'
    },
    filter = preset[$elem.attr('chars')] || $elem.attr('chars');

  regReplace = new RegExp('[^' + filter + ']', 'ig');
  $elem.val(value.replace(regReplace, ''));

});