如何检查我的Regex是否安全:不安全正则表达式lintsecurity/detect-unsafe-regex

fjaof16o  于 2023-08-08  发布在  其他
关注(0)|答案(1)|浏览(104)

我有一个帮助器,可以检查一个值是否是浮点数(德国数字用逗号代替圆点):

export const isFloat = (value: string) => {
    const pattern = /^[+-]?([0-9]+([,][0-9]*)?|[,][0-9]+)$/;
    return pattern.test(value);
};

字符串
但是,Eslint向我显示了此错误:
x1c 0d1x的数据
忽略这条规则安全吗?
或者我应该修正我的模式?如何检查我的正则表达式是否安全?

编辑1(第四只鸟评论)


EDIT2:

我也是,那我同事的函数也有同样的警告!


这是我的eslint配置:

module.exports = {
    root: true,
    parserOptions: {
        ecmaVersion: 2020,
        sourceType: "module",
        ecmaFeatures: {
            jsx: true,
        },
    },

    env: {
        browser: true,
        node: true,
        es6: true,
    },

    settings: {
        react: {
            version: "detect",
        },
        "import/resolver": {
            node: {
                extensions: [".ts", ".tsx"],
            },
        },
    },

    plugins: ["@typescript-eslint"],
    extends: [
        "next/core-web-vitals",
        "plugin:@typescript-eslint/recommended",
        "airbnb",
        "prettier",
        "plugin:jsx-a11y/recommended",
        "plugin:prettier/recommended",
        "plugin:sonarjs/recommended",
        "plugin:security/recommended", // this one
    ],

    rules: {
        "@typescript-eslint/no-unused-vars": "error",
        "@typescript-eslint/no-explicit-any": "error",
        "@typescript-eslint/explicit-function-return-type": "off",
        "react/react-in-jsx-scope": "off",
        "react/jsx-filename-extension": [
            1,
            {
                extensions: [".ts", ".tsx"],
            },
        ],
        "react/jsx-props-no-spreading": "off",
        "import/extensions": [
            "error",
            "ignorePackages",
            {
                js: "never",
                jsx: "never",
                ts: "never",
                tsx: "never",
            },
        ],
        "jsx-a11y/anchor-is-valid": [
            "error",
            {
                components: ["Link"],
                specialLink: ["hrefLeft", "hrefRight"],
                aspects: ["invalidHref", "preferButton"],
            },
        ],
        "no-nested-ternary": "off",
        "import/prefer-default-export": "off",
    },
};

ftf50wuq

ftf50wuq1#

在匹配时,您可以使用否定Assert来排除不允许的内容,然后匹配至少一个数字,而不是将量词嵌套在重复组中:

^[+-]?(?![\d,]*,,)(?![\d,]*,$)(?!,\d+,),*\d[\d,]*$

字符串

  • ^[+-]?可选匹配+-
  • (?![\d,]*,,)负前瞻,Assert非,,
  • (?![\d,]*,$)不是字符串末尾的,
  • (?!,\d+,)不是,,然后是数字和另一个,
  • ,*\d[\d,]*匹配可选,,后跟至少一个数字,然后是可选数字或,
  • $字符串结束

Regex demo

const safe = require('safe-regex');
const regex = /^[+-]?(?![\d,]*,,)(?![\d,]*,$)(?!,\d+,),*\d[\d,]*$/;
console.log(safe(regex));

// Output true

相关问题