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
2 Answers
Reset to default 5This 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
版权声明:本文标题:javascript - How to test input values using regex? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744269565a2598115.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论