Disallow insertion of special characters in a form using JS
Disallow insertion of special characters in a form using JS:
In case of form validation most of us check the values inserted inside the form fields only after the user submits the form. So, would not it be more efficient if we could avoid or disallow user to insert those values that could lead to unsuccessful form submission. A better approach could be by replacing those range of values using Regex and replacing it with an empty space.
It would be better to present it with an example.
Let us take a search bar where we have implemented the above method.
<div class = "form-group" >
<div class = "form-line" >
<label class = "font-weight-bold" > Search < /label>
<input type="text" id="Search" placeholder="Search"/>
</div>
</div>
So we have a search bar where we don’t want the user to insert special characters. So here we can use the js as given below for checking the inserted values.
//For replacing special characters......
$(document).on('keyup', "#Search", function () {
var h = $(this).val();
h = h.replace(/[`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, '');
$(this).val(h);
});
The above js inspects every key pressed within the search field and when any special character is inserted which is within the range of regex is automatically replaced with an empty space thus disallowing the user to insert any special characters.
Thus, This technique can be implemented for any type of form fields.
Also Read: Git commands you must know