admin管理员组

文章数量:1400591

I am working on one input application where i need to test input values that accepts single, multiple and even a range of numbers .

Eg inputs : 70,900,80-20 // should return true as all are valid
as,@123 // should return false as it is not valid digit
12-123-12123-123123 // should also return false

I am trying to use this in regex. I have tried this.

/^[\d,\-{1}]+/

I am not able to test using this regex. Let me know where i am doing wrong

I am working on one input application where i need to test input values that accepts single, multiple and even a range of numbers .

Eg inputs : 70,900,80-20 // should return true as all are valid
as,@123 // should return false as it is not valid digit
12-123-12123-123123 // should also return false

I am trying to use this in regex. I have tried this.

/^[\d,\-{1}]+/

I am not able to test using this regex. Let me know where i am doing wrong

Share Improve this question asked Jul 3, 2019 at 17:46 Shubham VermaShubham Verma 231 silver badge3 bronze badges 6
  • The rule regarding hyphens is that there can only be one but it can be followed by any number of integers? ^\d+(-?\d+)?$ – hungerstar Commented Jul 3, 2019 at 17:48
  • Which characters are valid? or simply put more examples. – mrReiha Commented Jul 3, 2019 at 17:48
  • @hungerstar Only one hyphen can be add . It just simple like number range for eg : 8-20 but this should not be valid 8-20-80 – Shubham Verma Commented Jul 3, 2019 at 17:51
  • @mrReiha only single hyphen and mas are allowed. – Shubham Verma Commented Jul 3, 2019 at 17:52
  • take a look at this -> /^\d+-?\d*$/ – mrReiha Commented Jul 3, 2019 at 17:56
 |  Show 1 more ment

2 Answers 2

Reset to default 5

This regular expression should work for you:

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

Explanation:

  • ^ means to start at the beginning of the string, to reject strings with extra stuff at the beginning
  • \d+(-\d+)? accepts a number optionally followed by a hyphen and another number:
    • \d+ means one or more digits
    • -\d+ means hyphen plus one or more digits
    • (...)? means the pattern inside the parentheses is optional
  • (,...)* accepts 0 or more instances of ma followed by the same pattern as above
  • $ says to match until the end of the string, to reject strings with extra stuff at the end

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

const input = document.querySelector( 'input' );
const msg   = document.querySelector( '.msg' );
const regex = /^\d+(-\d+)?(,\d+(-\d+)?)*$/;

input.addEventListener( 'keyup', function ( e ) {
  const str = regex.test( this.value ) ? 'Match!' : 'No Match';
  msg.textContent = str;
} );
<input type="text" name="numbers">
<div class="msg"></div>

本文标签: javascriptHow to test input values using regexStack Overflow