Validate input type="number" >= 1 with Angular

Asked

Viewed 1,671 times

-2

I am trying to do a validation so that the value of my input type="number" is >= 1. But I have tried several things and none of them worked. I am now trying to use ng-Pattern. But there is a loophole. If I type 0 it invalidates, but if I type 01 it validates!

<div ng-if="validaQtdPromotores(cadastro.cargo)" ng-class="{ 'has-error' : formCadastro.qtdPormotores.$invalid && !formCadastro.qtdPormotores.$pristine }">
   <input type="number" name="qtdPormotores" ng-model="cadastro.qtdPormotores" ng-pattern="/[1-9]/"  placeholder="Quantos promotores coordena?" required />
   <p ng-show="formCadastro.qtdPormotores.$invalid && !formCadastro.qtdPormotores.$pristine">Entre com um número válido.</p>
</div>
  • 01 is greater than or equal to 1, you do not want to accept any character 0?

  • The idea is that the number cannot start with zero. Ex: '0112'. So you can start with any number of 1-9 and have zeros afterwards!

2 answers

2

I think you’d better use the min=1 attribute in the input: <input type="number" min="1" name="qtdPormotores" ng-model="cadastro.qtdPormotores" placeholder="Quantos promotores coordena?" required />

  • Hi @Flavio Misawa. using the tag min="1" it returns to me the problem msm of Pattern q I am using. if type 0 invalida, but if type 01 validates!

2


You can modify your Pattern to:

/^[1-9][0-9]*$/

will not allow numbers starting at 0

  • Angular n accepted this expression: "Syntaxerror: Invalid regular Expression: / [1-9]+*$/: Nothing to repeat"

  • corrected, passed a * after the +

  • 1

    It’s almost that, but this invalid 10, 20, 30.. I mean, any number q has zero. The idea is to invalidate "0". Any number greater than q zero has q be valid!

  • Okay, the question is not clear, I updated the regex

  • That’s right! it worked now! : D tried almost that too! but when I put it I used one like this / [1-9]+[0-9]*$/ and then gave error! anyway thanks for the help! ;)

Browser other questions tagged

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