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

Form Submit and Validation

Ghislain B. edited this page May 7, 2015 · 18 revisions

The Angular-Validation concept was first introduced with the use ngDisabled on the submit button, but this might not always be the best option, so as another feature we could simply leave the submit button available but run an extra function to check the form validation before proceeding with our submit (that function is available through the ValidationService).

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

<!-- Option #1 - disable the submit button -->
<button type="submit" ng-disabled="form1.$invalid">Save</button>

<!-- Option #2 - click on submit button will call a function -->
<button type="submit" ng-click="submitForm()" ng-click="">Save</button>
// make sure to inject the `validationService` into your controller

// Option #2 will need to call the `checkFormValidity()` function checking the form before doing a real submit
// $validationSummary can be found in 2 variables (depending if your form as 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() {
  var myValidation = new validationService();
  if(myValidation.checkFormValidity($scope.form1)) {
    // proceed with submit
  }

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

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