regex in javascript allow only numbers and one dot followed by max 2 number
Everytime your event handler runs, the input grows by one character, so I think a better approach would be to check if the input still matches your regex rule and, if not, restore the previous value and force it to blur().
Try to update your event handler like this and it should work:
let curValue = '';
function onlyNumberAndADot(event) {
const valid = /^\d*\.?(?:\d{1,2})?$/;
const text = event.target.textContent;
if (!valid.test(text)) {
event.target.textContent = curValue;
event.target.blur();
} else {
curValue = event.target.textContent;
}
}
document.getElementById("test1").addEventListener("input", function(event) {
onlyNumberAndADot(event);
});
document.getElementById("test1").addEventListener("blur", function(event) {
event.target.textContent = event.target.textContent.replace(/\.$/,'');
});
I created a fiddle with this solution and it works.
Notice that you have to temporarily allow inputs like '0.', otherwise users won't be able to type in the dot, so I did another verification on blur event, to remove the final '.'
Allow only numbers and dot in script
Instead of using this:
onkeypress="return fun_AllowOnlyAmountAndDot(this);"
You should use this:
onkeypress="return fun_AllowOnlyAmountAndDot(this.id);"
Regex allow max 3 numbers and one dot
For on-submit (final) validation, you can use
^(?=.{3,4}$)\d+(?:\.\d+)?$
See the regex demo. It matches
^
- start of string(?=.{3,4}$)
- this requires the string to have three or four chars only\d+(?:\.\d+)?
- one or more digits, and then an optional occurrence of a.
and one or more digits. As\d
,\.
and\d
are obligatory to match at least once, the min limit as 3 is justified and since only one dot can be matched, either of\d+
can match one or two digits, but only three all in all$
- end of string.
For live input text validation, you can use
^(?:\d{1,3}|\d(?:\d?\.\d?|\.\d{2}))$
See the regex demo. Details:
^
- start of string(?:
- start of a group:\d{1,3}
- one, two or three digits
|
- or\d
- a digit(?:\d?\.\d?|\.\d{2})
- a non-capturing group matching either\d?\.\d?
- an optional digit, a.
and then an optional digit|
- or\.\d{2}
-.
and then two digits
)
- end of the group$
- end of string.
Regex allow digits and a single dot
If you want to allow 1
and 1.2
:
(?<=^| )\d+(\.\d+)?(?=$| )
If you want to allow 1
, 1.2
and .1
:
(?<=^| )\d+(\.\d+)?(?=$| )|(?<=^| )\.\d+(?=$| )
If you want to only allow 1.2
(only floats):
(?<=^| )\d+\.\d+(?=$| )
\d
allows digits (while \D
allows anything but digits).
(?<=^| )
checks that the number is preceded by either a space or the beginning of the string. (?=$| )
makes sure the string is followed by a space or the end of the string. This makes sure the number isn't part of another number or in the middle of words or anything.
Edit: added more options, improved the regexes by adding lookahead- and behinds for making sure the numbers are standalone (i.e. aren't in the middle of words or other numbers.
Limit 10 characters is numbers and only 1 dot
You could assert 10 chars in the string being either .
or a digit.
Then you can match optional digits, and optionally match a dot and again optional digits:
^(?=[.\d]{10}$)\d*(?:\.\d*)?$
The pattern matches:
^
Start of string(?=[.\d]{10}$)
Positive lookahead, assert 10 chars.
or digit till the end of string\d*
Match optional digits(?:\.\d*)?
Optionally match a `. and optional digits$
End of string
See a regex demo.
If the pattern should not end on a dot:
^(?=[.\d]{10}$)\d*(?:\.\d+)?$
Regex demo
How to restrict from entering any number with max 2 digits before and 8 digits after decimal in jquery
Instead of checking the numbers of event.which
you might use a single regex instead while typing to correct the input when something is entered that does not fit the required structure. Then when that occurs you could replace the wrong input with the last know valid input.
Note that you want to allow 0-2 digits, a dot and 0-8 digits which are 11 characters at max, so I think this $(this).val().length>9
should be 11.
As the previous pattern also allows a single dot at the end, you might when for example submitting a form, check the final value using this regex which checks if the value is either a 1-2 digits followed by a dot and 1-8 digits or |
a dot and 1-8 digits and does not accept an empty string.
^(?:\d{1,2}(\.\d{1,8})?|\.\d{1,8})$
Regex demo
let lastValid = "";$("#longitude").on("keypress keyup blur", function(event) { if (/^\d{0,2}(?:\.\d{0,8})?$/.test($(this).val())) { lastValid = $(this).val(); } else { event.preventDefault(); $(this).val(lastValid); }});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><form id="" name=""> <input type="text" value="" id="longitude"></form>
Related Topics
How to Open a Url Link from JavaScript Inside a Google Apps Script HTML Google Site Gadget
How to Specify a Single File to Be Seed Only
Call PHP Function With Onclick Event
How to Share and Edit Global Variables Between Two JavaScript Node Runs
Customizing Item-Text in V-Select
How to Detect String Which Contains Only Spaces
Passing Variable from One Js to Another Js File in Nodejs
React Native Flatlist With Clickable Items
How to Find Matching Values in Two Arrays
How to Force Clients to Refresh JavaScript Files
Securityerror: Blocked a Frame With Origin from Accessing a Cross-Origin Frame
Javascript Blob Filename Without Link
Draw a Connecting Line Between Two Elements
Validating Array of Different Object Shapes in Yup
Google Script to See If Text Contains a Value
How to Hide the Parent Div If All Its Child Div Are Hidden