JavaScript regular [removed]Page range validation)

前端 未结 4 947
失恋的感觉
失恋的感觉 2020-12-19 19:21

Yesterday I\'ve got a task to implement a validation on the field where user can enter the range of pages that he wants to download.

After reading some tutorials, I

相关标签:
4条回答
  • 2020-12-19 19:45

    ^((\\d+(\\-\\d+)?, ?)*(\\d+(\\-\\d+)?))+$

    0 讨论(0)
  • 2020-12-19 19:51

    You can try the regex:

    ^(\d+(-\d+)?)(,\d+(-\d+)?)*$
    

    To allow white spaces between you can do:

    ^(\s*\d+\s*(-\s*\d+\s*)?)(,\s*\d+\s*(-\s*\d+\s*)?)*$
    

    Rubular link

    0 讨论(0)
  • 2020-12-19 19:55

    You need to escape the backslashes in the string, or JavaScript will strip them out or interpret them as escape sequences:

    var patt1 = new RegExp("^(\\s*\\d+\\s*\\-\\s*\\d+\\s*,?|\\s*\\d+\\s*,?)+$");
    
    0 讨论(0)
  • 2020-12-19 20:00

    You can define patt1 without new RegExp, using a regular expression literal. Otherwise you'll have to escape all '\' in the regular expression string (using '\\').

    var patt1 = /^(\s*\d+\s*\-\s*\d+\s*,?|\s*\d+\s*,?)+$/g;
    

    now patt1.test("1, 2, 3-5, 6, 8, 10-12") should evaluate to true, patt1.test("1, 2, 3-5, 6, 8, 10-12,nocando") to false

    0 讨论(0)
提交回复
热议问题