Hunter Mitchell Hunter Mitchell - 4 months ago 9
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

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

Here is my controller:

var MyController = null;
app.controller("MyController", ["$scope", function($scope) {
$ = 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
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
for the original value to be placed back into the input and the model unchanged.


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

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

$ = function() {
  $scope.stored = $;

$scope.revertIfInvalid= function() {
  if (!$ {
    $ = $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) {