简体   繁体   中英

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
  • If i pass 10,6 it should validate no as per this restriction
  • If i pass 4,2 it should validate no as per this restriction

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() ).

With this provided, you can use the non-literal version of regex, which takes a string input:

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? 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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