angularjs form reset error
Asked Answered
K

13

40

i'm trying to do a form with validations using angularjs and so far i did a good job. But when i commit my reset button all the fields reset except for the error messages i get from my validation part. How can i get rid of all the fields and error messages when i reset my form.

This is how it is when i press my reset button

enter image description here

this is my code

<div class="page-header"><center><h2>Give us your Feedback</h2></center></div>

    <!-- pass in the variable if our form is valid or invalid -->
    <form name="userForm" ng-submit="submitForm(userForm.$valid)" novalidate>

        <!-- NAME -->
        <div class="form-group" ng-class="{ 'has-error' : userForm.name.$invalid && !userForm.name.$dirty }">
            <label>Name*</label>
            <input type="text" name="name" class="item-input-wrapper form-control" ng-model="user.name"  required>
            <p ng-show="userForm.name.$invalid && !userForm.name.$pristine " class="help-block">
                <font color="#009ACD">You name is required.</font>
            </p>
        </div>

         <!-- EMAIL -->
        <div class="form-group" ng-class="{ 'has-error' : userForm.email.$invalid && !userForm.email.$dirty  }">
            <label>Email</label>
            <input type="email" name="email" class="item-input-wrapper form-control" ng-model="user.email" required >
            <p ng-show="userForm.email.$invalid && !userForm.email.$pristine" class="help-block">
                <font color="#009ACD">Enter a valid email.</font>
            </p>
        </div>

        <!-- USERNAME -->
        <div class="form-group" ng-class="{ 'has-error' : userForm.username.$invalid && !userForm.username.$dirty }">
            <label>Description</label>
            <input type="text" name="username" class="item-input-wrapper form-control" ng-model="user.username"  ng-minlength="5" ng-maxlength="60" required>
            <font color="white">
                <p ng-show="userForm.username.$error.minlength" class="help-block">
                    <font color="#009ACD">Description is too short.</font>
                </p>
                <p ng-show="userForm.username.$error.maxlength" class="help-block">
                    <font color="#009ACD">Description is too long.</font>
                </p>
            </font>
        </div>

        <div class="col"style="text-align: center">
            <button align="left"class="button button-block button-reset"style="display: inline-block;width:100px;text-align:center "
                type="reset"
                ng-click="reset()" padding-top="true"
            >
                Reset
            </button>


            <button class="button button-block button-positive"  style="display: inline-block;width:100px "
                ng-click="submit()"
                padding-top="true"
            >
                Submit
            </button>
        </div>

    </form>
</div>

My controller

.controller('ContactCtrl', function($scope,$state,$ionicPopup, $timeout) {
    $scope.showfeedback = function() {
        $state.go('app.sfeedback');
    };

    $scope.submitForm = function(isValid) {
        $scope.submitted = true;

        // check to make sure the form is completely valid
        if (!isValid) {
            var alertPopup = $ionicPopup.alert({
                title: 'Invalid data entered!',
            });
        } else {
            var alertPopup = $ionicPopup.alert({
                title: 'Feedback submitted',
            });
        }
    };

    $scope.reset = function() {
        var original = $scope.user;
        $scope.user= angular.copy(original)
        $scope.userForm.$setPristine()
    };
})
Kyd answered 24/9, 2014 at 10:50 Comment(5)
post the code for resetting ?Reclusion
is there in the button it self. i have given type="reset".it clears the form but not the error messagesKyd
Try $scope.user = undefined;Saccharose
Did you try removing type="reset" ?Shaunna
when i remove type = 'reset' it won't resetKyd
R
41
var original = $scope.user;

when resetting :

$scope.user= angular.copy(original);
$scope.userForm.$setPristine();

remove

type='reset' in  <button>

here is the Angular Documentation for form controllers.

Reclusion answered 24/9, 2014 at 10:54 Comment(7)
put var original = $scope.user; in out side the reset functionReclusion
i put it outside the reset function.still won't workKyd
@Kyd Try $scope.user = undefined;Saccharose
i did. i dont know why but when i click reset button it's doing what my submit button should do. strangeKyd
that's because when u use a button without a type in a form that button is in type="submit" defaultReclusion
Don't forget to try $scope.userForm.$setUntouched() / $touched flag that was introduced on angular 1.3!Sheriesherif
#18648927Pipe
Y
34

Use the following to reset dirty state

$scope.form.$setPristine();

Use the following to reset to clear validation

$scope.form.$setValidity();
Younglove answered 15/1, 2015 at 3:1 Comment(0)
E
25

There's API documentation on the FormController.

This allowed me to find that there's other methods to call such as:

$setUntouched() - which is a function I was using if the user has focused on the field, and then left the field, this clears this feature when you run it.

I created a simple form reset function which you can use too.

// Set the following in your controller for the form/page.
// Allows you to set default form values on fields.
$scope.defaultFormData = { username : 'Bob'}
// Save a copy of the defaultFormData
$scope.resetCopy = angular.copy($scope.defaultFormData);
// Create a method to reset the form back to it's original state.
$scope.resetForm =  function() {
    // Set the field values back to the original default values
    $scope.defaultFormData = angular.copy($scope.resetCopy);
    $scope.myForm.$setPristine();
    $scope.myForm.$setValidity();
    $scope.myForm.$setUntouched();
    // in my case I had to call $apply to refresh the page, you may also need this.
    $scope.$apply();
}

In your form, this simple setup will allow you to reset the form

<form ng-submit="doSomethingOnSubmit()" name="myForm">
    <input type="text" name="username" ng-model="username" ng-required />
    <input type="password" name="password" ng-model="password" ng-required />
    <button type="button" ng-click="resetForm()">Reset</button>
    <button type="submit">Log In</button>
</form>
Ence answered 23/7, 2015 at 23:55 Comment(2)
the $setUntouched(); was the missing link for meSamoyed
Glad I could have helped!Ence
C
4

I went with...

$scope.form.$setPristine();
$scope.form.$error = {};

Feels hacky... but a lot about angular does.

Besides... this was the only thing that worked.

Claret answered 4/2, 2016 at 15:1 Comment(0)
B
3

I had the same problem and used the following code to completely reset the form :

$scope.resetForm = function(){

    // reset your model data
    $scope.user = ...

    // reset all errors
    for (var att in  $scope.userForm.$error) {
        if ($scope.userForm.$error.hasOwnProperty(att)) {
            $scope.userForm.$setValidity(att, true);
        }
    }

    // reset validation's state
    $scope.userForm.$setPristine(true);
};
Bestraddle answered 26/9, 2014 at 11:47 Comment(0)
F
2

To me using $setPristine to reset the form is a hack. The real solution is to keep it like it should be:

<button type="reset" ng-click="reset()"></button>

then in angular:

var original = angular.copy($scope.user);
$scope.reset = function() {
   $scope.user = angular.copy(original);
};

and that's it.

Foredeck answered 30/8, 2016 at 20:24 Comment(0)
S
1

Use this

<button type="button" ng-click='resetForm()'>Reset</button>

In Controller

$scope.resetForm = function(){
   $scope.userForm.$dirty = false;
   $scope.userForm.$pristine = true;
   $scope.userForm.$submitted = false;
};

Its working for me

Saccharose answered 24/9, 2014 at 11:26 Comment(1)
@Kyd I have update the answer try now and let me know if you got any error in console.Saccharose
O
1

In case you don't have a master (dynamic models from server), and you want to reset the form but only the binded part of the model you can use this snippet:

  function resetForm(form){
    _.forEach(form, function(elem){
      if(elem !== undefined && elem.$modelValue !== undefined){
        elem.$viewValue = null;
        elem.$commitViewValue();
      }
    });
  }

And then you can use it with a standard reset button like so:

<button type="reset" ng-click="resetForm(MyForm);MyForm.$setValidity();">reset</button>
Osteopathy answered 14/8, 2015 at 14:56 Comment(1)
Very helpful! This also resolved an issue with resetting of ngModel values. Intentionally setting it null and committing it to the ngForm did the trick.Dimphia
T
1

Give us your Feedback

<!-- pass in the variable if our form is valid or invalid -->
<form name="userForm" ng-submit="submitForm(userForm.$valid)" novalidate>


    <!-- NAME -->
    <div class="form-group" ng-class="{ 'has-error' : userForm.name.$invalid && !userForm.name.$dirty }">
        <label>Name*</label>
        <input type="text" name="name" class="item-input-wrapper form-control" ng-model="user.name"  required>
        <p ng-show="userForm.name.$invalid && !userForm.name.$pristine " class="help-block"><font color="#009ACD">You name is required.</font></p>


    </div>

     <!-- EMAIL -->
    <div class="form-group" ng-class="{ 'has-error' : userForm.email.$invalid && !userForm.email.$dirty  }">
        <label>Email</label>
        <input type="email" name="email" class="item-input-wrapper form-control" ng-model="user.email" required >
        <p ng-show="userForm.email.$invalid && !userForm.email.$pristine" class="help-block"><font color="#009ACD">Enter a valid email.</font></p>
    </div>

    <!-- USERNAME -->
    <div class="form-group" ng-class="{ 'has-error' : userForm.username.$invalid && !userForm.username.$dirty }">
        <label>Description</label>
        <input type="text" name="username" class="item-input-wrapper form-control" ng-model="user.username"  ng-minlength="5" ng-maxlength="60" required>
        <font color="white"><p ng-show="userForm.username.$error.minlength" class="help-block"><font color="#009ACD">Description is too short.</font></p>
        <p ng-show="userForm.username.$error.maxlength" class="help-block"><font color="#009ACD">Description is too long.</font></p>
    </div>

    <div class="col"style="text-align: center">
        <button align="left"class="button button-block button-reset"style="display: inline-block;width:100px;text-align:center "
        type="reset"
        ng-click="reset()"padding-top="true">Reset</button>


        <button class="button button-block button-positive"  style="display: inline-block; width:100px" ng-click="submit()"padding-top="true">Submit</button>
        </div>

</form>

Tolyl answered 12/2, 2016 at 7:51 Comment(0)
R
1

In My Form

<form angular-validator-submit="submitReview()" name="formReview"  novalidate angular-validator>

 <input type="text" name="Rating" validate-on="Rating" class="form-control"
   ng-model="Review.Rating" required-message="'Enter Rating'" required>
  <button type="button" ng-click="reset()">Cancel</button>
 </form>


app.controller('AddReview', function ($scope) {

    $scope.reset= function () {
        $scope.formReview.reset() 
    };
});

only need to call $scope.formReview.reset() where formReview is my form name.

Rapid answered 18/2, 2016 at 10:3 Comment(0)
C
1

I kept the type="reset" in my button. What I did was the ng-click="resetForm(userForm)" (using userFrom to match your example) and the controller defines resetForm() as

scope.resetForm = function(controller) {
  controller.$commitViewValue();
  controller.$setPristine();
};

Here is what happens:

  1. When the reset button is clicked, it will bring back the original values as specified by the value attribute on the input
  2. The $commitViewValue() will force the write of whatever is on the view presently to the $modelValue of each field (no need to iterate manually), without this the last $modelValue would still be stored rather than reset.
  3. The $setPristine() will reset any other validation and submitted fields.

In my angular-bootstrap-validator I already had the FormController as such I didn't need to pass in the form itself.

Carpeting answered 8/3, 2016 at 23:0 Comment(0)
S
0

My form is inside another scope so my solution need to use $$postDigest

$scope.$$postDigest(function() {
    $scope.form.$error = {};
});
Scamp answered 4/2, 2020 at 3:8 Comment(0)
C
-3

To reset the validations we have to do two things:

  1. clear the fields
  2. Add the following:

    $scope.programCreateFrm.$dirty = false;
    $scope.programCreateFrm.$pristine = true;
    $scope.programCreateFrm.$submitted = false;
    

programCreateFrm is the name of the form. For example:

<form name="programCreateFrm" ng-submit="programCreateFrm.$valid && createProgram(programs)" novalidate>

This code is working for me.

Clingstone answered 25/1, 2016 at 11:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.