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

Reset Form

Ghislain B edited this page Mar 23, 2017 · 10 revisions

Angular-Validation proposes multiple ways of resetting a form with subtle variations. You can reset the form without necessarily making the form ever valid (it will simply make it visually reset and untouched, but it is still an invalid form in the background), or you could also make it completely reset (remove all validators & make the form valid). The resetForm() function is called through the ValidationService and requires at least 1 argument being your form object, and function works with both the Directive & Service.

Some examples (works for both the Directive & Service)

Reset Form (visual reset, form remains invalid)

This is the default behavior, you can see it in the Plunker Live Demo under the Directive or Service pages. Click on Reset Form, then click on Submit checkFormValidity() will still show as an invalid form (if not filled correctly).

myApp.controller('Ctrl', function ($scope) {
  // reset the form without passing any options
  $scope.resetForm = function() {
    new ValidationService().resetForm($scope.form1);
  };
});
Reset Form with options (remove all validators, everything becomes valid)

You can see this behavior in the Plunker Live Demo under 2 Forms page. Once clicking on Reset Form, all input values will be cleared and your form will never be invalid again since there is no more validators associated.

// inject the ValidationService inside your Controller
myApp.controller('Ctrl', function ($scope, ValidationService) {
  // reset the form and pass some options
  $scope.resetForm = function() {
    new ValidationService().resetForm(
      $scope.form1, 
      { 
        emptyAllInputValues: true,  // user filled some input already, do you want to empty all these input values? False by default
        removeAllValidators: true   // do you want to remove all validators? False by default. 
      }
    );
  };
});

You have to be aware that passing the option of removeAllValidators to true will make your form always valid. So calling the checkFormValidity() would always be valid. In most cases, it's probably not what you want, so by default it is defined as false.

Notes

When no options are passed, it equals to having both options of emptyAllInputValues and removeAllValidators as being false.

Clone this wiki locally