简体   繁体   English

如何在JavaScript中创建动态正则表达式以验证十进制数字

[英]How to create Dynamic Regular Expression in javascript to validate decimal number

I have to validate a decimal number based on the digits provided before the decimal and after the decimal. 我必须根据十进制之前和十进制之后提供的数字来验证十进制数字。 Say i have a function which is having a regular expression and takes two parameters as digits before the decimal and digits after the decimal. 说我有一个具有正则表达式的函数,并接受两个参数作为小数点前的数字和小数点后的数字。

function validateDecimalNo(digitBeforeDec,digitAfterDec){
          //here i need to write the regular expression to validate the  decimal no based on the inputs.
            }
  • If i pass 2,3 it should check decimal no as per this restriction 如果我通过2,3,则应按照此限制检查小数点否
  • If i pass 10,6 it should validate no as per this restriction 如果我通过10,6,则应按照此限制验证否
  • If i pass 4,2 it should validate no as per this restriction 如果我通过4,2,则应按照此限制验证否

How to create the single dynamic regular expression to meet above requirement. 如何创建单个动态正则表达式来满足上述要求。

In JavaScript, you have literal syntax ( /regex/ , {object} , or even "string" ), and you have the non-literal syntax ( new RegExp() , new Object() , new String() ). 在JavaScript中,您具有文字语法( /regex/{object}甚至是"string" ),并且具有非文字语法( new RegExp()new Object()new String() )。

With this provided, you can use the non-literal version of regex, which takes a string input: 借助此功能,您可以使用非文字版本的regex,该版本需要输入字符串:

var myRegex = new RegExp("hello", "i"); // -> /hello/i

So, this provided, we can make a function that creates a "dynamic regex" function (quotes because it's actually returning a new regex object every time it's run). 因此,提供了这一点,我们可以创建一个创建“动态正则表达式”函数的函数(引用,因为它实际上每次运行时都会返回一个新的正则表达式对象)。

For instance: 例如:

var getRegex = function(startingSym, endingSym, optional){
  return new RegExp(startingSym + "(.+)" + endingSym, optional)
}

So, with this example function, we can use it like this: 因此,通过此示例函数,我们可以像这样使用它:

var testing = getRegex("ab", "cd", "i");
console.log(testing);
// Output:
/ab(.+)cd/i

Why use regexp? 为什么要使用regexp? Just check the number directly. 只需直接检查电话号码即可。

function make_decimal_validator(digitBeforeDec,digitAfterDec) {
    return function(no) {
        var parts = no.split('.');
        if (parts.length !== 2) throw "Invalid decimal number";
        return parts[0].length === digitBeforeDec && parts[1].length === digitAfterDec;
    };
}

Make your validator: 使您的验证器:

var validator23 = make_decimal_validator(2, 3);
validator23('12.345') // true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM