Search code examples
javascriptregexinputsanitization

Is this input sanitization regex safe?


I have an input field where I expect the user to enter the name of a place (city/town/village/whatever). I have this function which is use to sanitize the content of the input field.

sanitizeInput: function (input) {
        return input.replaceAll(/[&/\\#,+()$~%.^'":*?<>{}]/g, "");
    }

I want to remove all special characters that I expect not to appear in place name. I thought a blacklist regex is better than a whitelist regex because there are still many characters that might appear in a place name.

My questions are:

  1. Is this regex safe?
  2. Could it be improved?
  3. Do you see a way to attack the program using this regex?

EDIT: This is a tiny frontend-only project. There is no backend.


Solution

  • Your regex is perfect to remove any special characters. The answers are :

    1.the regex is safe , but as you mentioned it is a vuejs project so the js function will run on browser. Browsers basically not safe for doing user input sanitization. You should do that in backend server also , to be 100% safe

    1. You can not improve the regex itself in this example. But instead of regex , you could use indexOf for each special characters also ( it will be fastest process but more verbose and too much code) Like : str.indexOf('&') !== -1 str.indexOf('#') !== -1 Etc

    3.same as answer 1,the regex is safe but as it is used in browser js , the code an be disabled , so please do server side validation also.

    If you have any issue with this answer ,please let me know by comment or reply.