Missing step attribute error message in input

时间:2016-04-25 09:14:34

标签: angularjs validation input angular-material

Angular js does provide a validation for several html5 introduced attributes of an input, like min or requiredincluding the .

<input type="number" name="input1" id="input1" min="0" 
        ng-model="$ctrl.input1"ng-required />
<div ng-messages="formname.input1.$error" class="em-messages">
    <div ng-message="required">This value is required</div>
    <div ng-message="min">You must not use negative values</div>
</div>

For the step attribute such a validation is working, but no error message can be displayed the material way by default, so what's the easiest way to implement it (for example for step="0.001"?

<input type="number" name="input1" id="input1" min="0" step="0.001"
        ng-model="$ctrl.input1"ng-required />
<div ng-messages="formname.input1.$error" class="em-messages">
    <div ng-message="required">This value is required</div>
    <div ng-message="min">You must not use negative values</div>
    <div ng-message="step">You can work with 0.001 steps</div>
</div>

1 个答案:

答案 0 :(得分:0)

Simple, just use a regex like this:

<input type="number" name="input1" id="input1" min="0" step="any"
        ng-model="$ctrl.input1"ng-required 
         ng-pattern="/^[0-9]\d*((.|,)\d{1,3})?$/" />
<div ng-messages="formname.input1.$error" class="em-messages">
    <div ng-message="required">This value is required</div>
    <div ng-message="min">You must not use negative values</div>
    <div ng-message="pattern">You can work with 0.001 steps</div>
</div>

To eplain the regex quickly:
[1-9]\d* means that there can be any natural numbers
((.|,)\d{1,3})? now a . or a , can follow to seperate the fraction
\d{1,3} defines that there have to be one to three numbers have to follow

Now your pattern will show an error message in angular material style.

Depending on how your step should actually look like, you will have to modify either the \d{1,3}, to reflect the amount past commata numbers and maybe wrap into a modulo, so if you want todo something link step="0.005".