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>
    <link rel="stylesheet" href="style.css">
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.0/angular.min.js"></script>
     <script src="//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>

  <body ng-app="myApp" ng-controller="myCtrl">
     <form name="myForm" novalidate ng-submit="submitForm()">
         <label>
             Enter your name:
             <input type="text" name="myName" ng-model="name" ng-minlength="5" ng-maxlength="20" required />
         </label>

         <div ng-if="myForm.$submitted || myForm.myName.$dirty" ng-messages="myForm.myName.$error" style="color:red" role="alert">
             <div ng-message="required">You did not enter a field</div>
             <div ng-message="minlength">Your field is too short</div>
             <div ng-message="maxlength">Your field is too long</div>
         </div>
         <br>
         <br>
         <label>
             Enter your phone number:
             <input type="number" name="myPhone" ng-model="phone" ng-maxlength="20" required />
         </label>

         <div ng-if="myForm.$submitted || myForm.myPhone.$dirty" ng-messages="myForm.myPhone.$error" style="color:red" role="alert">
             <div ng-message="required">You did not enter a field</div>
             <div ng-message="maxlength">Your field is too long</div>
         </div>
         <br>
         <br>

         <button type="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"