Samantha J T Star
Samantha J T Star

Reputation: 32838

How can I do validation and use ..$setPristine(); in an AngularJS form?

I have the following code:

            <form class="form"
                  data-ng-submit="modalSubmit(modal.data)"
                  id="modal-body"
                  name="modalForm"
                  novalidate>

This works and when I click on a button of type submit then the modalSubmit function is called.

However I would like to do this in my controller:

$scope.modalForm.$setPristine();  

But it gives an error saying:

has no method '$setPristine'

How I can I set the form to pristine? I did try adding data-ng-form="modalForm" but then I get a message saying something to the effect of duplicate directive names.

I tried changing the form element to a DIV but then the clicking on the submit button does not call the function

Here's an example (modified from another user) that shows what I am trying to do which is set values to pristine:

plnkr.co/edit/LNanJdAggMLIgxii0cfv?p=preview

Upvotes: 4

Views: 9139

Answers (3)

ms87
ms87

Reputation: 17492

You're not doing anything wrong there, only problem is you're referencing an old version of angular in which $setPristine() was not a feature. $setPristine() was added in 1.1.+, so reference a newer version of angular and you're good to go. See it working in this plunk, using 1.2.+.

If you can't upgrade, then a dirty workaround would be to loop through all inputs in the form and set their $dirty and $pristine values manually:

$scope.mp = function() {
  $scope.mainForm.$pristine=true;//clean main form
  $scope.mainForm.$dirty=false;
  angular.forEach($scope.mainForm,function(input){//clean all input controls
    if (input !== undefined && input.$dirty !== undefined) {
      input.$dirty=false;
      input.$pristine=true;
    }
  });
}

Upvotes: 6

boatcoder
boatcoder

Reputation: 18127

First, your version of angular was old, 1.2.12 is the latest stable on the CDN. But even it wouldn't allow $setPristine because of the HTML5 validation that was going on.

The biggest problem was you used required on the fields instead of ng-required. The browser was doing the form validation for you instead of angular. You could also add the novalidate attribute to the form tag.

http://plnkr.co/edit/l1mUCceSFMFFZWgGgL6u?p=preview

Upvotes: 3

Lalit Sachdeva
Lalit Sachdeva

Reputation: 6639

it has already been implemented in this link you can use it this was as it has been demonstrated in the plnkr link. As you can see from the above description, $setPristine only changes the state of the form (and thereby resets the css applied to each control in the form).

If you want to clear the values of each control, then you need to do for each in code.

Upvotes: 0

Related Questions