Hunter Mitchell Hunter Mitchell - 6 months ago 15
AngularJS Question

Handling Input validation in AngularJs?

I am very new to angularjs and I just cant figure out how I would go about validating my inputs.

I have an input which should never be empty. The model will always have a value. Whenever a user inputs invalid data (i.e nothing or maybe invalid characters) I would like the input to revert to its original value.

For instance, If the initial value was

50
and I deleted all of that (or entered text) and deselected the input, I would expect the input's value to change back to
50
.

Here is my controller:

var MyController = null;
app.controller("MyController", ["$scope", function($scope) {
$scope.data = myData;
$scope.validate = function(value, oldValue) {
if(!value || value == "") {
// Do something after validation
value = oldValue;
}
// Our value should be valid now (either replaced or changed)
}
MyController = $scope;
}]);


And my HTML (i would rather not have to type
data.something
twice if possible):

<input type="text" ng-model="data.something" ng-change="validate()" />


Small Clarification: If the value of the input is "50" and a user removes the "0", the input would be at "5" which is valid. However if the user adds a "x" after I DONT want the input to change, it should still be at "5". However if all the input is empty, I would like
onBlur
for the original value to be placed back into the input and the model unchanged.

Answer

Yep, you need ng-blur and probably ng-focus:

<input type="text" ng-model="data.something" ng-focus="store()" ng-blur="revertIfInvalid()"/>

$scope.store = function() {
  $scope.stored = $scope.data.something;
}

$scope.revertIfInvalid= function() {
  if (!$scope.data.something) {
    $scope.data.something = $scope.stored;
  }
}

This will work, but to make it reusable, you then want to make directive for this, like:

app.directive('fancydirective', function() {
  return {
    restrict: 'A',
    require: 'ngModel',
    link: function(sc, elem, attrs, ngModelCtrl) {
      var stored;
      elem.on('focus', function() {
        sc.$apply(function() {
          stored = ngModelCtrl.$modelValue;
        });
      });
      elem.on('blur', function() {
        sc.$apply(function() {
          if (ngModelCtrl.$invalid) {
            ngModelCtrl.$setViewValue(stored);
            ngModelCtrl.$render();
          }
        });
      });
    }
  }
});

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

Comments