Gary Holiday
Gary Holiday

Reputation: 3562

How to manually change the $error values for input tags - Angularjs

I am submitting a form via the angular $http and I want to give an error if the user bypassed the angularjs validation. I want to use the same error tag as if they didn't bypass the validation, userForm.name.$invalid && !userForm.name.$pristine how can I manually set this value ?

HTML

  <body>
    <form ng-controller="UserController" ng-model="userForm" name="userForm" ng-submit="createUser()">

      <legend>Create User</legend>

      <label>Name</label> 
      <input type="text" id="name" name="name" ng-model="user.name" placeholder="User Name" required>
      <!-- HERE IS WHERE THE ERROR SHOWS -->
      <p ng-show="userForm.name.$invalid && !userForm.name.$pristine"

      <button class="btn btn-primary">Register</button>

    </form>
  </body>

ANGULAR JS

  $http({
    method : 'POST',
    url : '/create',
    data : user,
    headers : {
      'Content-Type' : 'application/x-www-form-urlencoded'
    }
  })
  .success(function(data) {
    // I want to do something like this 
    name.$invalid = true;
    name.$pristine = false;
  });

I want to do something like what is in the success function. Therefore it will show the error message.

Upvotes: 1

Views: 2517

Answers (3)

Kyle
Kyle

Reputation: 5557

If you want to check a specific field for validity, you can use a custom directive:

app.directive('customValidation', function(dataService) {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attrs, ctrl) {
            ctrl.$parsers.unshift(function(viewValue){
                //first, assume the value is valid, until proven otherwise
                ctrl.$setValidity('customValidation', true);

                //check against the API
                if(viewValue.length > 0 && !ctrl.$error.customValidation) {
                    dataService.checkValidity(viewValue).then(function(response){
                        //API logic here
                        var results = response.data;
                        if(results.isNotValid)
                            ctrl.$setValidity('customValidation', false);
                    }).catch(function(response){
                        //some error occurred
                        ctrl.$setValidity('customValidation', false);
                    });
                }
            });
        }
    };
});

To use it:

<input custom-validation ng-model-options="{updateOn: 'default blur', debounce: { 'default': 700, 'blur': 0 }}" />

Upvotes: 0

Chris Story
Chris Story

Reputation: 1197

To set the validity or pristine values of the form, you must use the function provided by the form.FormController. You can set the form to pristine or dirty but you cannot set a form directly to valid to not. You must set a particular model to invalid which will trigger the form value to invalid which will trigger the form to be invalid (https://docs.angularjs.org/api/ng/type/form.FormController).

//UserController
//$scope.userName is your object which has it's own controller using Angular Forms.

app.controller("UserController", function($scope){
 $http({
    method : 'POST',
    url : '/create',
    data : user,
    headers : {
      'Content-Type' : 'application/x-www-form-urlencoded'
    }
  })
  .success(function(data) {
    // I want to do something like this 
    $scope.userForm.$setDirty(); //Sets $pristine to false;  Alternatively, you could call $setPristine() to set $pristine to true
    $scope.userForm.name.$setValidity("length",false); //In your case, the "length" validation is likely something different or will be generic.  This enables you to have name fail validation based multiple rules (perhaps length and unique)
  });
});

Upvotes: 0

Muthukannan Kanniappan
Muthukannan Kanniappan

Reputation: 2079

If you have access to scope in http success callback, you can do this to set the validity or mark it as dirty.

scope.userForm.name.$setDirty();

OR

scope.userForm.name.$setValidity('serverError', false); // creating a new field in $error and makes form field invalid.

Upvotes: 1

Related Questions