Form validation using ngMessages directive , in AngularJS

24 views
Skip to first unread message

jaden behr

unread,
Oct 18, 2017, 6:40:03 AM10/18/17
to Angular and AngularJS discussion

Hello, 

I'm facing a certain problem -  I'm trying to validate a textfield phone number. 

When the field is empty (after interacting with the input), I want the message "This field is required" to be shown, and when the user starts typing, I want the message to show "Invalid Phone Number" , until a certain pattern is met (using ngPattern). When the pattern is met, all messages should stay hidden.

Code in HTML:
<form name="PhoneForm">
        <div>
            <md-icon md-svg-src="icons/ic_phone_48px.svg"></md-icon>
            <md-input-container>
                <label>Phone Number</label>
                <input ng-model="contactPhone" name="PhoneInput" required ng-pattern="/^(05){1}[0-9]{8}$/"/> <!-- i.e 05x-xxxxxxx -->
                <div ng-messages="PhoneForm.PhoneInput.$error" ng-if="PhoneForm.PhoneInput.$invalid">
                    <div ng-message="required">This field is required</div>
                    <div ng-message="pattern">Invalid Phone Number</div>
                </div>
            </md-input-container>
        </div>
    </form>
 
The problem is that when the pattern is met, the message "Invalid Phone Number" is shown twice. I know it has something to do with the ng-if directive and $invalid, I just can't figure out how to fix it. I also tried replacing $invalid with $dirty but it did not solve the problem.

Would appreciate any help.
Thank you.


Sander Elias

unread,
Oct 30, 2017, 6:27:35 AM10/30/17
to Angular and AngularJS discussion
Hi Jaden,

It should not be doing that. Can you provide a plunker that show this behavior, that way it becomes possible to look at your issue.

Regards
Sander






Reply all
Reply to author
Forward
0 new messages