This is my regex which restricts any characters other than numbers -(minus) and .(dot) Regex is as follows
(?!^-)[^0-9\.]
which allows - (minus) only at the start, But i would like to know If i can allow .(dot) only once and restrict the user to type the next .(dot)
My code
oninput => "this.value = this.value.replace(/(?!^-)[^0-9\.]/g,'')"
CodePudding user response:
You want to allow:
- Optional leading minus (
-?
) - At least one digit (
\d
) - Optional suffix: a dot, followed by at least one digit (
\.\d
)
An appropriate regex is:
^-?\d (?:\.\d )?$
CodePudding user response:
As I understand, the user is to be restricted to entering the string representation of an integer or float (possibly negative), and that restrictions are to be imposed on a character-to-character basis. You therefore need a sequence of dynamically-constructed regular expressions that each match a single-character string.
I assume the user enters RETURN to signal that no more characters are to be entered. The user is to be permitted to enter RETURN only when the previous entry was a digit.
- Define
r = /[-\d]/
. - The first character entered must match
r
. - If the first character entered is
'-'
, setr = /\d/
, else (as the first character was a digit) setr = /[\d.]/
. - If the previous character was a period update
r = /\d/
and require the user to enter a character that matchesr
(i.e, a digit); else the user may press RETURN or enter a character that matchesr
(which could be/\d/
or/[\d.]/
). - Repeat step 4 until the user presses RETURN.
Note that, in step 4, once r
is set /\d/
it remains at that value until the user presses RETURN.
If a user entry (including RETURN) is rejected it would be helpful to display a message giving the reason for it being rejected.