Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I prevent write and paste special characters inside input fields?

I am trying to prevent inputs from writing and inserting special characters. This will prevent characters from being written, but will not prevent them from being inserted. How can i do it with JQuery?

 $('#first').keypress(function (e) {
    var txt = String.fromCharCode(e.which);
    if (!txt.match(/[A-Za-z0-9&. ]/)) {
        return false;
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="form" action="reg.php" method="POST" id="reg" onsubmit="return formSubmit();">
    <input type="text" name="first" id="first" required/>
    <input type="text" name="sec" id="sec" required />
</form>
like image 210
Noah Avatar asked Dec 31 '25 02:12

Noah


2 Answers

You can use the below REGEX to prevent from special characters

var nospecial=/^[^*|\":<>[\]{}`\\()';@&$]+$/;

$('#first').keypress(function (e) {
    var txt = nospecial.test(e.val());
    if (!txt) {
        $('#first').val('');
        return false;
    }
});
like image 80
Praveen Kumar Avatar answered Jan 01 '26 15:01

Praveen Kumar


You'll need to bind to the paste event and run a replace on the string to remove characters you don't want. This example will allow pasting, but will strip out characters that aren't allowed.

Solution

$('#first').keypress(function (e) {
  var txt = String.fromCharCode(e.which);
  if (!txt.match(/[A-Za-z0-9&. ]/)) {
      return false;
  }
});

$('#first').bind('paste', function() {
  setTimeout(function() { 
    var value = $('#first').val();
    var updated = value.replace(/[^A-Za-z0-9&. ]/g, '');
    $('#first').val(updated);
   });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="first" />

Notes

  • In the bind function, I added ^ to your matching group to match everything that isn't those characters.
  • You could update your regular expression to /a-z0-9&.\s/i. \s means space (it's more readable than an actual space), and i means case-insensitive.
  • If you want to allow _ characters, you could use \w instead of A-Za-z0-9, in which case, you could also use \W to match the opposite.

Documentation

https://developer.mozilla.org/en-US/docs/Web/Events/paste

like image 42
AnonymousSB Avatar answered Jan 01 '26 16:01

AnonymousSB