Shubham Verma
Shubham Verma

Reputation: 23

How to test input values using regex?

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

Upvotes: 2

Views: 5776

Answers (2)

hungerstar
hungerstar

Reputation: 21725

/^\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>

Upvotes: 2

joanis
joanis

Reputation: 12228

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

Upvotes: 5

Related Questions