Purpose of JSLint “disallow insecure in regex” opt

2019-01-23 11:21发布

问题:

I have a line of code that gets the following error when run through JSLint:

Lint at line 604 character 48: Insecure '^'.
numExp = parseInt(val[1].replace(/[^\-+\d]/g, ""), 10);

This error seems to refer to the following description from JSLint's option page:

"true if . and [^...]  should not be allowed in RegExp literals.
These forms should not be used when validating in secure applications."

I don't quite understand how a client-side javascript application can really be considered secure. Even with the most airtight regex, it's still possible to fire up something like firebug and change the variable anyway. The real input validation should be done on the server, and the client browser should probably stick with validation that will handle the abuse of your average user.

Is it safe to ignore this error? Am I missing an angle here where my application will be insecure because of client-side input validation?

回答1:

"Insecure" means "unspecific" in this context. Both the dot . and the exclusive range [^…] are not clearly defining what should be matched by the regex. For validation purposes, this can propose the risk of successfully matching stuff that you did not think of and do not want (think: white-listing vs. black-listing).

In any case, dot and exclusive range are valid parts of a regular expression, and if they do what you need (like in this case), I would think of the warning as over-cautious.

A malicious user can fiddle with your page logic any time; the warning is more about the regular operation of the page.



回答2:

All it's trying to tell you is that it's generally better to specify what can be entered instead of what can't.

In this case, your regex is actually stripping out bad characters, so it's safe to ignore the warning.