2

I'm developing multi-page web application (not an Angular SPA). In some cases I have to render pages with embedded validation errors (like failed login attempt after HTTP POST). I want these errors to be displayed by angular on page load. I've created custom validator (directive called it odd for now). But it seems that the only way to have them displayed is to blur from each individual input field.

<md-input-container>
  <label>Email</label>
  <input name="j_username" type="email" ng-model="j_username" odd="false" md-autofocus />
  <div ng-messages="login.j_username.$error">
    <span ng-message="odd">Some error message prerendered on a server side</span>
  </div>        
</md-input-container>

Here is a link to codepen: http://codepen.io/anon/pen/RGRgoN Click on email and then loose focus, you'll see error message appears.

Question is: how to force angular to display all validation messages for all fields on a form on page load?

Sergey Karpushin
  • 874
  • 1
  • 10
  • 33

2 Answers2

0

Probably it's a shortcut, but after I added this setTimeout to my custom validator errors started to appear on page load as needed. If anyone aware of a better way please let me know!

app.directive("hasVe", function() {
    return {
        restrict : "A",
        require : "ngModel",

        link : function(scope, element, attributes, ngModel) {
            var hasVe = attributes.hasVe;
            ngModel.$validators.hasVe = function(modelValue) {
                return hasVe !== "true";
            };

            // NOTE: This looks like a shortcut, but it works
            setTimeout(function() {
                ngModel.$touched = true;
                scope.$apply();
            }, 100);
        }
    };
});

Here is an updated snippet: http://codepen.io/anon/pen/RGRmpY

Sergey Karpushin
  • 874
  • 1
  • 10
  • 33
0

Just came across this issue myself. This thread was helpful: show validation error messages on submit in angularjs

What you want to do is add ng-show="login.$submitted" to your ng-messages element. ng-messages will still work the way it did before, where error messages pop up if the input has been 'touched' or modified, but it also adds what you want, which is to show the error messages if the user attempts to submit.

when a user attempts to submit a form, the angular form variable login.$submitted gets set to true (even if the submit was not successful)

<div ng-messages="login.j_username.$error" ng-show="login.$submitted">
    <span ng-message="odd">Some error message prerendered on a server side</span>
</div> 

also, make sure to include ngMessages in your app initiation: https://docs.angularjs.org/api/ngMessages#module-installation

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

this is definitely required if you are using Angular Material. and then you don't even need to use the ng-show="login.$submitted"

Max
  • 454
  • 4
  • 10