Trigger validation of all fields in Angular Form submit

后端 未结 13 1338
悲哀的现实
悲哀的现实 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:03

    Here is my global function for showing the form error messages.

     function show_validation_erros(form_error_object) {
            angular.forEach(form_error_object, function (objArrayFields, errorName) {
                angular.forEach(objArrayFields, function (objArrayField, key) {
                    objArrayField.$setDirty();
                });
            });
        };
    

    And in my any controllers,

    if ($scope.form_add_sale.$invalid) { 
        $scope.global.show_validation_erros($scope.form_add_sale.$error);
    }
    
    0 讨论(0)
  • 2020-12-08 02:03

    To validate all fields of my form when I want, I do a validation on each field of $$controls like this :

    angular.forEach($scope.myform.$$controls, function (field) {
        field.$validate();
    });
    
    0 讨论(0)
  • 2020-12-08 02:04

    In case someone comes back to this later... None of the above worked for me. So I dug down into the guts of angular form validation and found the function they call to execute validators on a given field. This property is conveniently called $validate.

    If you have a named form myForm, you can programmatically call myForm.my_field.$validate() to execute field validation. For example:

    <div ng-form name="myForm">
        <input required name="my_field" type="text" ng-blur="myForm.my_field.$validate()">
    </div>
    

    Note that calling $validate has implications for your model. From the angular docs for ngModelCtrl.$validate:

    Runs each of the registered validators (first synchronous validators and then asynchronous validators). If the validity changes to invalid, the model will be set to undefined, unless ngModelOptions.allowInvalid is true. If the validity changes to valid, it will set the model to the last available valid $modelValue, i.e. either the last parsed value or the last value set from the scope.

    So if you're planning on doing something with the invalid model value (like popping a message telling them so), then you need to make sure allowInvalid is set to true for your model.

    0 讨论(0)
  • 2020-12-08 02:06

    You can use Angular-Validator to do what you want. It's stupid simple to use.

    It will:

    • Only validate the fields on $dirty or on submit
    • Prevent the form from being submitted if it is invalid
    • Show custom error message after the field is $dirty or the form is submitted

    See the demo

    Example

    <form angular-validator 
           angular-validator-submit="myFunction(myBeautifulForm)"
           name="myBeautifulForm">
           <!-- form fields here -->
        <button type="submit">Submit</button>
    </form>
    

    If the field does not pass the validator then the user will not be able to submit the form.

    Check out angular-validator use cases and examples for more information.

    Disclaimer: I am the author of Angular-Validator

    0 讨论(0)
  • 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:

     <form ng-submit='justDoIt()'>
    

    becomes:

     <form name='myForm' novalidate submit='justDoIt()'>
    

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

    0 讨论(0)
  • I like the this approach in handling validation on button click.

    1. There is no need to invoke anything from controller,

    2. it's all handled with a directive.

    on github

    0 讨论(0)
提交回复
热议问题