I'm trying to devise a regular expression which will accept decimal number up to 4 digits. I have successfully done it when a user types it in a text box. Now, I'm trying to validate text box for paste operation. For that, I have written a jquery function
function pasteNumber() {
var reNumber = /\d*\.\d{0,4}/;
var theString = window.clipboardData.getData('Text');
if (reNumber.test(theString) == false) {
alert("You are trying to paste an invalid Number!")
return;
}
event.srcElement.value = theString
return;
}
The regular expression which I have used is accepting a value like
44.aaaa
which it should not accept. Then I tried changing regular expression to
/\d*\.\d{1,4}/
Then, it started to accept values like
44.1aaa
I need help to write a regular expression which will accept values like
4.1
421.11
467.111
438904.1111
0.1
But not
1234.a
489.a
435.aaa
412.1aaaa
1567.11a
In short, there should be no characters.
Any suggestions please? Thank you
You are only missing the anchors ^
and $
^\d*\.\d{0,4}$
See demo
But, to avoid matching .
and 123.
, you can enhance it as
^\d*\.\d{1,4}$
See update .
As for anchors , they
do not match any character at all. Instead, they match a position before, after, or between characters. They can be used to the regex match at a certain position. 在特定位置。 The caret
^
matches the position before the first character in the string. Applying^a
toabc
matchesa
.^b
does not matchabc
at all, because theb
cannot be matched right after the start of the string, matched by^
.Similarly,
$
matches right after the last character in the string.c$
matchesc
inabc
, whilea$
does not match at all.
You just need to add some anchors and group (?:)
the entire decimal part and make it optional with a ?
:
^\d+(?:\.\d{1,4})?$
^
is for start of string, $
is for end of string
See demo
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.