Your problem is that the attribute pattern
does not serve to determine that the input
will only accept writing numbers inside it. The Pattern serves to validate the input
. If it has letters it will be invalid, but if it’s just numbers it’ll be valid.
See what Mozilla says about the attribute pattern
HTML5:
A regular expression used to validate the control value. The default
should match the full value of the input, not just a part. Use
the title attribute to describe the pattern to help the user. This
attribute is applied when the value of the type attribute is text, search,
tel, url or email; otherwise it is ignored. The language of
regular expression is the same as Javascript. The default should not be
between bars.
Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input
For further clarification you can refer to this question: How to use the Pattern attribute?
Practical example of use
See this example to better understand validation with Pattern in the front using CSS. Note that input
type="number"
you can only type numbers in. In the other it is type="text"
it is only valid if you type numbers, if they are letters it continues with the red border :invalido.
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" >
Why don’t you use Html5
<input type="number">
?– MarceloBoni
Possible duplicate of input only numbers with jquery
– Thiago Magalhães
Detail, I believe it works, the problem is that Pattern does not prevent the user to enter numbers, it just does not allow sending the form with numbers
– MarceloBoni
To prevent this, only with Javascript.
– Sam
@sam I left a -1 not only because the question is not clear enough because it does not say what exactly "does not work", even if it works perfectly as expected, but also because the user be active on the site more than 4 years, be one of the most question (maybe the second) and still ask this way. Since I am active on the site, I see bad questions from it, is usually oriented to edit, but still does not seem to strive to maintain the quality of the site.
– Woss