Validate field to accept integer and decimal numbers

Asked

Viewed 1,352 times

2

How to do with Javascript, so that one input text type accepted only whole numbers and decimal numbers up to 2 decimal places.

Ex:

1    - true
1,1  - true
1,11 - true


$("body").on("input", ".number", function(event){
    $(this).val(this.value.replace(/\D/g, ''));
})

2 answers

5

You can use the property pattern, that defines the format the field can have, using a regular expression for that:

/* deixa uma borda vermelha enquanto o campo estiver inválido */
input:invalid {
    border: 1px solid red;
}
<form>
<input type="text" pattern="^\d+(,\d{1,2})?$" required>
</form>

Explaining the regex:

\d+ is "one or more digits".

Then we have an excerpt between parentheses: a comma followed by \d{1,2} (one or two digits). And the ? after the parentheses makes all this excerpt optional.

That is, we can have multiple digits, or multiple digits followed by comma, followed by one or two digits.

In addition, the regex has the markers ^ and $, which are respectively the beginning and end of the string. Thus, I guarantee that the field will only have what is specified in regex.


What your replace(/\D/g, '') is replacing all the \D (that is, any character that nay is digit) by '' (the empty string). That is, you are removing everything that is not a digit from the field value (if the value is, for example, abc123!@#,:.x, the result of replace will be 123 - everything that is not digit is removed). So it does not work to validate the field format.

0

input { box-sizing: border-box; width: 100%; border: 1px solid; outline: none; }
:valid { border-color: green; }
:invalid { border-color: red; }
<input pattern="\d+,?\d{0,2}" autofocus>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.