Reputation: 81
I'm trying to achieve this regular expression check. (1 integer, 3 digits)
Valid:
Invalid:
I would like to have only 1 digit follow by a decimal with only 0-3 decimal places.
Any help would be great. I have tried this:
^(([0-9]{1})?(?=\.)[0-9]{0,3})|([0-9]{1})$
but no lock.
Edit: I should have added that I'm using a JQuery plugin called inputmask. I would like for the inputmask to only accept my requirement.
Upvotes: 0
Views: 73
Reputation: 1074168
I would like to have only 1 whole number follow by a decimal with only 0-3 decimal places.
By "1 whole number" I take it you mean one digit, as 12
is a single whole number. If so:
\d\.\d{0,3}
That matches a single digit followed by a .
followed by zero to three digits. If you want to further assert that it matches the entire string, add anchors to either end:
^\d\.\d{0,3}$
Note that the rules you've given allow for 1.
, which seems like you may not want. If you don't, then we need to do a bit more work:
^\d(?:\.\d{1,3})?$
That says: One digit optionally followed by a .
with 1-3 digits. It has the "whole string" anchors, remove them if you don't want them.
Live Example using that last one:
var input = document.querySelector("input");
var rex = [
/\d\.\d{0,3}/,
/^\d\.\d{0,3}$/,
/^\d(?:\.\d{1,3})?$/
];
input.oninput = input.onpaste = input.onkeypress = updateDisplay;
function updateDisplay() {
rex.forEach(function(r, index) {
var display = document.getElementById("r" + index);
if (!input.value) {
display.innerHTML = "--";
} else if (input.value.match(r)) {
display.innerHTML = "valid";
} else {
display.innerHTML = "INVALID";
}
});
}
<input type="text">
<p><code>/\d\.\d{0,3}/</code> says: <span id="r0"></span></p>
<p><code>/^\d\.\d{0,3}$/</code> says: <span id="r1"></span></p>
<p><code>/^\d(?:\.\d{1,3})?$/</code> says: <span id="r2"></span></p>
Upvotes: 1
Reputation: 26434
To do this with jquery-inputmask
, use this
<input id="example2" data-inputmask-regex="/^\d{1}\.\d{0,3}$/" />
And then in your JavaScript file, add this
$(document).ready(function(){
$("#example2").inputmask("Regex");
});
Here is the Regex breakdown
^
- Regex must start with this expression
\d{1}
- Exactly 1 digit from 0 to 9
\.
- Followed by a period. Important to note that periods must be escaped
\d{0,3}
- Followed by 0 to 3 digits
$
- Regex must end with this expression
I tested for all of your examples.
Upvotes: 1