Trigger validation of all fields in Angular Form submit

后端 未结 13 1369
悲哀的现实
悲哀的现实 2020-12-08 01:45

I\'m using this method: http://plnkr.co/edit/A6gvyoXbBd2kfToPmiiA?p=preview to only validate fields on blur. This works fine, but I would also like to validate them (and thu

13条回答
  •  粉色の甜心
    2020-12-08 02:08

    One approach is to force all attributes to be dirty. You can do that in each controller, but it gets very messy. It would be better to have a general solution.

    The easiest way I could think of was to use a directive

    • it will handle the form submit attribute
    • it iterates through all form fields and marks pristine fields dirty
    • it checks if the form is valid before calling the submit function

    Here is the directive

    myModule.directive('submit', function() {
      return {
        restrict: 'A',
        link: function(scope, formElement, attrs) {
          var form;
          form = scope[attrs.name];
          return formElement.bind('submit', function() {
            angular.forEach(form, function(field, name) {
              if (typeof name === 'string' && !name.match('^[\$]')) {
                if (field.$pristine) {
                  return field.$setViewValue(field.$value);
                }
              }
            });
            if (form.$valid) {
              return scope.$apply(attrs.submit);
            }
          });
        }
      };
    });
    

    And update your form html, for example:

     

    becomes:

     
    

    See a full example here: http://plunker.co/edit/QVbisEK2WEbORTAWL7Gu?p=preview

提交回复
热议问题