ng-pattern doesn't show $error.pattern
Asked Answered
B

1

15

I have script here and ng-pattern works correctly because scope.subnet is shown in Output only after input matches pattern. But ng-show doesn't display any error if ng-pattern is not matched

<body ng-contoller="myConfigGenCtr">
  <form novalidate name="myForm">
            <div class="form-group">
                <label for="hostname">Firewall hostname</label>
                <input type="text" ng-model="hostname" class="form-control" id="hostname">
            </div>
            <div class="form-group">
                <label for="subnet">Firewall subnet</label>
                <input type="text" ng-model="subnet" class="form-control" id="subnet"
                       required ng-pattern="/^(?:[0-9]{1,3}\.){3}/" >
                <div class="custom-error"  ng-show="myForm.subnet.$error.pattern">
                    Not a valid subnet, should be i.e. 10.x.y. (3 bytes only)</div>
            </div>
        </form>
  <div>Output: {{subnet}}</div>      
</body>
Bainmarie answered 13/8, 2015 at 18:21 Comment(2)
what pattern should match? could you give some example?Tubate
i.e. 1.1.1. it displays fine. But if i type 1.1 error doesnt show upBainmarie
T
26

When you add form tag with its name, angular does create a scope variable for that name attribute value & do add all the form fields of the form which have name attributes. Those fields attribute variable get created inside form scope object. Like here you are using myForm that means $scope.myFrom has all the information about the form fields. like its validity using $valid, $invalid, $error, etc.

Here you are using ng-show="myForm.subnet.$error.pattern" on subnet element of form. You missed to add name="subnet" attribute on input field, that turns out to subnet element validation doesn't available inside myForm scope variable.

Markup

<input type="text" name="subnet" ng-model="subnet" class="form-control" 
id="subnet" required ng-pattern="/^(?:[0-9]{1,3}\.){3}/" >

Working Plunkr

Tubate answered 13/8, 2015 at 18:49 Comment(3)
Very nice and simple answer, thanks @Pankaj, I was missing calling it on the pattern attr. Didn't know you could do this.Bumpy
@Bumpy glad to hear that it helped you. Thanks & cheers ;)Tubate
@ShubhamTiwari you could use [attr.pattern]="/^(?:[0-9]{1,3}\.){3}/"Tubate

© 2022 - 2024 — McMap. All rights reserved.