-1

I have tried the following regular expression for my validation but it is resulting in false and im not able to get the solution. I want it to validate for Max 15 digits excluding 4 decimal places. Can anybody guide me through this?

    var patt = new RegExp("[-+]?\d{1,15}(\.\d{1,4})?$");
    var res = patt.test(txtFxRateAgainstUSD.value);
    if (!res)
    {
        errMsg = errMsg + "Enter Rate in valid format: (Max 15 digits excluding 4 decimal places).\r\n";
    }
  • Double escape it: `new RegExp("^[-+]?\\d{1,15}(\\.\\d{1,4})?$");` or use regex literal `/^[-+]?\d{1,15}(\.\d{1,4})?$/` – anubhava Jul 25 '16 at 11:09
  • Could you clarify *I want it to validate for Max 15 digits excluding 4 decimal places* requirement? Any sample inputs? You also need the start of string anchor `^` at the start, BTW. And surely use a regex literal notation. – Wiktor Stribiżew Jul 25 '16 at 11:10

1 Answers1

2

Try escaping the digit character d and dot character . with double slash.So that your string literal can express it as data before transforming it into a regular expression.

Code:

var regPattern = new RegExp("^[-+]?\\d{1,15}(\\.\\d{1,4})?$");

if(!regPattern.test(txtFxRateAgainstUSD.value)) 
{
    errMsg = errMsg + "Enter Rate in valid format: (Max 15 digits excluding 4 decimal places).\r\n";
}
Lokesh_Ram
  • 391
  • 4
  • 10
  • 1
    There is no use in a RegExp constructor notation if the pattern is static. Use the regex literal notation. Also, it is not a good idea to take someone else's comment and use it in your answer. Even if you tested it. Can you at least explain why it should work? – Wiktor Stribiżew Jul 25 '16 at 11:22
  • 1
    Thanks @Lokesh_Ram – user3682373 Jul 25 '16 at 14:05