Skip to content
This repository has been archived by the owner on Jul 1, 2020. It is now read-only.

Form Submit and Validation

Daniel Pinto edited this page Oct 15, 2015 · 18 revisions

The Angular-Validation concept was first introduced with the use ngDisabled on the submit button, but you could also leave the submit button available but run an extra function to check the form validity before proceeding with our submit (that function is available through the ValidationService as checkFormValidity()).

You could also use the Validation Summary for displaying all errors as a header, footer or anywhere you want to place it

<!-- Option #1 - click on submit button will call a function -->
<button type="submit" ng-click="submitForm()" ng-click="">Save</button>

<!-- Option #2 - disable the submit button -->
<button type="submit" ng-disabled="form1.$invalid">Save</button>
// inject the validationService inside your Controller
myApp.controller('Ctrl', function ($scope, validationService) {

  // Option #1 requires a call to `checkFormValidity()`. checking the form before doing a real submit
  // $validationSummary can be found in 2 variables (depending if your form has a name or not)
  // you can use `checkFormValidity($scope.yourFormName)` or this `checkFormValidity($scope)`
  // If your form does not have a name attribute, your only choice is `checkFormValidity($scope)`
  $scope.submitForm = function() {
    if(new validationService().checkFormValidity($scope.form1)) {
      // proceed with submit
    }

    // or without a form name, use the $scope alone
    if(new validationService().checkFormValidity($scope)) {
      // proceed with submit
    }
  }

  // Option #2 - You could also use the $validationSummary to be displayed after a Submit
  // and prevent it from submitting any remaining errors
  $scope.submit = function (event) {
    if($scope.form1.$invalid) {
        $scope.displayValidationSummary = true;
        event.preventDefault();
    }
  }
});
Clone this wiki locally