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>
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;
}
});
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.
$('#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" />
bind function, I added ^ to your matching group to match everything that isn't those characters./a-z0-9&.\s/i. \s means space (it's more readable than an actual space), and i means case-insensitive._ characters, you could use \w instead of A-Za-z0-9, in which case, you could also use \W to match the opposite.https://developer.mozilla.org/en-US/docs/Web/Events/paste
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With