Skip to content Skip to sidebar Skip to footer

Angular : Ng-message Validation On Submit Click

I am working on application where I've one form and It should show validation error message for input fields on wrong input. My form will look like this - It should show error mes

Solution 1:

You can use $submitted for the form,

Syntax: formname.$submitted

$submitted : True if user has submitted the form even if its invalid.

<!DOCTYPE html><html><head><linkrel="stylesheet"href="style.css"><scriptsrc="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.0/angular.min.js"></script><scriptsrc="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.0/angular-messages.js"></script><script>var app = angular.module('myApp', ['ngMessages']);
         app.controller('myCtrl', function($scope) {

             $scope.submitForm = function() {
                 
                 if (myForm.$valid) {
                     alert('Form submitted with passed validation');
                 }
             };

         });
    </script></head><bodyng-app="myApp"ng-controller="myCtrl"><formname="myForm"novalidateng-submit="submitForm()"><label>
             Enter your name:
             <inputtype="text"name="myName"ng-model="name"ng-minlength="5"ng-maxlength="20"required /></label><divng-if="myForm.$submitted || myForm.myName.$dirty"ng-messages="myForm.myName.$error"style="color:red"role="alert"><divng-message="required">You did not enter a field</div><divng-message="minlength">Your field is too short</div><divng-message="maxlength">Your field is too long</div></div><br><br><label>
             Enter your phone number:
             <inputtype="number"name="myPhone"ng-model="phone"ng-maxlength="20"required /></label><divng-if="myForm.$submitted || myForm.myPhone.$dirty"ng-messages="myForm.myPhone.$error"style="color:red"role="alert"><divng-message="required">You did not enter a field</div><divng-message="maxlength">Your field is too long</div></div><br><br><buttontype="submit">Submit</button></form></body></html>

Please run this snippet and check.

Here is the reference

The changed plunker link of yours

Solution 2:

Update Plunker Link

You could go with disabling submit button till your form isn't correct one

Post a Comment for "Angular : Ng-message Validation On Submit Click"