Member-only story
How to Sanitize Your Form Inputs
Sanitizing your form inputs not only helps protect your software from cyberattacks. It also prevents bad data from polluting your databases and makes your code less likely to break in other places as a result.
Fortunately, it is pretty easy to add to any forms or inputs you may have. Having some knowledge of regular expressions will help greatly.
Vanilla Javascript
If you are working with plain HTML and Javascript, the easiest thing to do is add an event listener to your input. Let’s assume you have an input for name with an id = “name”. We select your form input and then assign it a listener on the “input” event.
const nameEntry = document.getElementById("name");
nameEntry.addEventListener(
"input",
function (e) {
let val = e.target.value;
return val.replace(/[^A-Za-z\s]/gi, "");
}
);
This will replace any character being entered that is not an uppercase letter, lowercase letter, or space with an empty string. If a user tries to type in a semicolon or something malicious, it simply will not let them.
You can do even more with this. Maybe you have an email input, and you would rather not give a user the opportunity to type in a bad email.
const emailEntry = document.getElementById("email")…