Validate only number in the input [closed]

-8

I have this html

<input formControlName="sGPTypeDeliveryId" type="text" placeholder="Tipo de Entrega" class="form-control" required="required" pattern="[0-9]+$">

Using the pattern attribute should work, but with me it is not working. How do I only allow number in the input?

    
asked by anonymous 23.07.2018 / 21:04

3 answers

2

Your problem is that the pattern attribute does not serve to determine that input will only accept typing numbers within it. The pattern is for you to validate input . If it has letters it will be invalid , but if they are only numbers it will be valid .

See what Mozilla says about the pattern attribute of HTML5:

  

A regular expression used to validate the value of the control. The standard   must marry the full value of the entry, not just one part. Use   the title attribute to describe the default to help the user. This one   attribute is applied when the value of the type attribute is text, search,   tel, url or email; otherwise it is ignored. The language of the   Regular expression is the same as JavaScript. The standard should not be   between bars.

Source: link

For more clarification you can consult this question: How to use the pattern attribute?

Practical example of use

See this example to better understand validation with pattern in front using CSS. Note that not input type="number" you can only enter numbers inside. In the other that is type="text" it is only valid if you enter numbers, if they are letters it continues with the red border: invalid.

input:invalid {
  border-color: red !important;
}
input:valid {
  border-color: green !important;
}
  <link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />

Esse input só vai ser válido se tiver apenas números
<input formControlName="sGPTypeDeliveryId" type="text" placeholder="apenas números ou será inválido" class="form-control" required="required" pattern="[0-9]+$">
    
Esse input é do type="number" ele só deixa escrever números dentro
<input type="number" class="form-control" >
    
23.07.2018 / 21:30
1

In the input type, just enter number. It looks like this:

<input formControlName="sGPTypeDeliveryId" type="number" placeholder="Tipo de Entrega" class="form-control" required="required">
    
23.07.2018 / 21:11
0

There are two ways to get the result with just HTML. The first using regular expression in the pattern attribute and the second using the type number .

<form>
  <input formControlName="sGPTypeDeliveryId" type="text" placeholder="Tipo de Entrega" class="form-control" required="required" pattern="\d*">
  <input formControlName="sGPTypeDeliveryId" placeholder="Tipo de Entrega" class="form-control" required="required" type="number" step="1" />
  <input type="submit" />
</form>
    
23.07.2018 / 21:14