ps0604 February 2016

How to validate forms with dynamic ngMessages

This plunk has a form with a field that only allows to enter aaa. Note that the error message is set in the controller, not in the html. When the user clicks on Submit they should see the message, but the message is not shown. What's wrong with this code?

HTML

<body ng-app="ngMessagesExample" ng-controller="ctl">

  <form name="myForm" novalidate ng-submit="submitForm()">
    <label>
      This field is only valid when 'aaa' is  
      <input type="field1"
             ng-model="data.field1"
             name="field1"
             required />
    </label>
    <div ng-messages="myForm.field1.$error" style="color:red">
        <div ng-message-exp="required">{{errorMsg}}</div>
    </div>

  <br/><br/>
  <button style="float:left" type="submit">Submit</button>
</form>

</body>

Javascript

var app = angular.module('ngMessagesExample', ['ngMessages']);

app.controller('ctl', function ($scope) {

  $scope.submitForm = function() {
    if ($scope.field1 != 'aaa')
        $errorMsg = "This field should be 'aaa'";
    else
        $errorMsg = "";
  };      

});

Answers


dendimiiii February 2016

Forget my previous answer. Easiest and most robust is actually to make a new directive.

var app = angular.module('ngMessagesExample', ['ngMessages']);
app.directive("aaa", function() {
    return {
        restrict: "A",

        require: "ngModel",

        link: function(scope, element, attributes, ngModel) {
            ngModel.$validators.aaa = function(modelValue) {  
                return modelValue === 'aaa';
            }
        }
    };
});

And your controller:

app.controller('ctl', function ($scope) {

  $scope.data = {
    field1: ""
  }
  $scope.submitForm = function(){
     //extra whatever code
  }
});

Your HTML should be this:

<body ng-app="ngMessagesExample" ng-controller="ctl">
  <form name="myForm" novalidate ng-submit="submitForm(myForm)">
    <label>This field is only valid when 'aaa' is</label>  
    <input type="field1"
         ng-model="data.field1"
         name="field1"
         required aaa/>
    <div ng-messages="myForm.field1.$error" style="color:red">
      <div ng-message="required">FIELD IS REQUIRED!!</div>
      <div ng-message="aaa">FIELD MUST BE 'aaa'</div>
    </div>
    <button style="float:left" type="submit">Submit</button>
  </form>
</body>

Post Status

Asked in February 2016
Viewed 1,022 times
Voted 10
Answered 1 times

Search




Leave an answer