简体   繁体   中英

How does “input type=number” show an error message if the user inputs “five hundreds”

If the user does not type a number in the field (for instance "five hundred", or "9987-"), angular does not handle it as an error, and no error is shown (the ng-class is not changed in this example).

<div class="form-group"
     ng-class="{ 'has-error' : submitted && form.price.$error.pattern }">
        <input name="price" id="price" type="number"
               ng-model="formOb.price"
               ng-pattern="/^[0-9]+([\.|,][0-9]+)?$/"
                />

Is there a way to handle that ? How could the class be changed to 'has-error' ? (it would be better if no direct javascript is used, if possible)

ng-pattern works only when you bind html tag with name. Only name attribute is required for making you example up and running.

Check this link for more details: Angularjs Forms

Set the type as a "text" - Angular will catch this via ng-pattern - if you use type="number", then some browser may not even pass the input value to be checked with your pattern.

<div class="form-group"
     ng-class="{ 'has-error' : submitted && form.price.$error.pattern }">
        <input name="price" id="price" type="text"
               ng-model="formOb.price"
               ng-pattern="/^[0-9]+([\.|,][0-9]+)?$/"
                />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM