Home > Software engineering >  I want to include special character but no 'Path like patters' from user input
I want to include special character but no 'Path like patters' from user input

Time:12-17

I have a problem. I want to have a regex, which allows alphanumerics along with / - _ ( ) . & I make the patterns like this

[-\w\/().&]

But there's catch, I also don't want my regex to allow a distinctive patterns, something like

..////
...////

means ads.fsd/ can be allowed but asd./asd can't not be allowed.

I have checked the following inputs which are passing in the updated regex in javascript, I have used regex101.com to verify the following inputs :

dsf-sdfd
dsf.dsf
dsfdsf/dsfdsf
dfdf./dsfdsf
dsf(dsf)dsfsdf
dsf&sdfsdf
dsfds.///..//sdfsdf

But I don't want patterns like this to pass cause this input will be blocked by the WAF library for security purposes.

dfdf./dsfdsf
dsfds.///..//sdfsdf

Cause they are sensed like paths

And I want to try my best in doing that filter in single regex cause it will be used in a textbox and it only takes one pattern, i don't want to circuit second regex using javascript, if it can be possible, I tried some but it was all vain.

CodePudding user response:

Your problem sounds like matching tokens that include one or more valid characters, /-_().&, but you don't want dots followed by any slash, i.e., ./ is forbidden. To achieve that, you may first exclude . from inside the [], and then add . back to the pattern - but with negative lookahead. So the result looks like

const pattern = /^([-\w\/()&]|\.(?!\/)) $/

The ([-\w\/()&]|\.(?!\/)) part means, to match

  1. [-\w\/()&] or
  2. \. that is NOT followed by a \/.

CodePudding user response:

You can solve this without RegEx by creating an array with unsafe substrings and then filtering the input for these characters:

var input = document.querySelector("textarea[input]").value.replace(/\r/g, "").split("\n").map(item => item.trim());

var unsafe = [
  "../",
  "./",
  "//"
];

var safe = input.filter((item) => unsafe.filter((us) => item.includes(us)).length == 0);
safe.forEach((item, i) => {
  console.log(item);
});

// If you want to check on a String use this:
input = "dsfdsf/dsfdsf";
var isSafe = unsafe.filter(item => input.includes(item)).length == 0;

console.log(input   ": "   isSafe);
<textarea input hidden>
  dsf-sdfd
  dsf.dsf
  dsfdsf/dsfdsf
  dfdf./dsfdsf
  dsf(dsf)dsfsdf
  dsf&sdfsdf
  dsfds.///..//sdfsdf
 </textarea>

Maybe is this solution more logical than regex for understanding the filter method look here: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

  • Related