The Browser tab starts when my RegEx runs and does not match the input

The problem is as follows. I created an input field that has validation, and this is valid data:

  • 1-12, 14, 16, 22, 25-35, 41, 49, 55-90
  • 1230-1992, 2001-2099, 9931
  • 1-2
  • thirteen
  • 1,3,4,5,6,10
  • everything

Basically, any combination of these numbers (ranges, ranges separated by commas, a number with a comma, spaces after a comma, spaces after commas, a word: "all")

My RegEx: / ^ (([[0-9] {0,4},? \ S {0,}) + ([0-9] {1,4} - [0-9] {1,4}) {0}, \ s {0,}) + $ | ^ (all) $ |? ^ ([0-9] {1,4} - [0-9] {1,4}) {0,}, \? s {0,} $ /

It works almost fine, there is only one serious problem.

When I start typing and after some numbers separated by commas, I add something invalid, for example, the characters: 'abc' - and at that moment my browser tab stucks.

Try this as an input: 1-12, 14, 16, 19, 20-29,

Script to verify: http://jsfiddle.net/c9ahfhqy/

Are there any suggestions as to what the correct RegEx should look like?

the code:

$("input[type='text']").blur(function() { //when you lose focus on input doneTyping(); }); function doneTyping() { if(!$('#inputToCheck').val().match(/^(([0-9]{0,4},?\s{0,})+([0-9]{1,4}\-[0-9]{1,4}){0,},?\s{0,})+$|^(all)$|^([0-9]{1,4}\-[0-9]{1,4}){0,},?\s{0,}$/)) { console.log("Not Valid"); } else { console.log("Valid"); } } 

Carefully appreciate the help.

+7
javascript browser regex web backtracking
source share
1 answer

As @derp said , your regex has a Catastrophic rollback problem.

The following seems to work the way you want and does not delay the browser:

 /^(?:all|\d{1,4}(?:-\d{1,4})?(?:,\s*\d{1,4}(?:-\d{1,4})?)*)$/ 

Demo

Using the RegexBuddy debugger to test 1-12, 14, 16, 19, 20-29, was ,

  • You are re-executing the error after trying 1,000,000 steps with this error:

    Your regex is too complicated to continue debugging.
    The regular expression mechanism that you plan to use may not cope with all this and crashes.
    See "catastrophic backtracking" in the help file to find out how to avoid this situation.

  • Repeating the above expression fails after 96 steps without errors.

+5
source share

All Articles