I'm working on a form where I'd like to have some custom validation rules like:

field 2 has to be larger than field 1

field 3 is required if field 2 is not negative

...

HTML

<table>
<tr><th>Category</th><th> > </th> ≤ <th></tr>

<tr><td>Green</td>
    <td><input type="number" id="field1" ng-model="green.low"/></td>
    <td><input type="number" id="field2" ng-model="green.high"/></td></tr>
</table>

JS

I check the validation this way:

function verifyForm(form, scope) {
    if (form.$error.required) {
        scope.addAlert("danger", "[![base.error.msg.required_fields]]");
        return false;
    }
    if (!form.$valid) {
        scope.addAlert("danger", "[![base.error.msg.invalid_form]]");
        return false;
    }
    return true;
};

So when the submit button is clicked, I just have to do this:

if (!verifyForm($scope.formName, $scope))
        return;

How can I add those custom validation rules? Or, if I have to write them myself in javascript, how can I "invalidate" certain elements?

share
up vote 1 down vote accepted

for field2 valid use:

<input type="number" max={{field1}}>

for field3 use:

<input type="number" ng-required="field2>0">
share

I think the right Angular approach to this kind of problem is creating directives that perform custom validation.

It's not very intuitive, and you'll probably have to spend a few minutes learning the basic idea, but when it works, it's actually one of the great powers of Angular.

Here's how a validator for 'greater-than-other-input' might look like:

angular.module('myApp', []).directive('gtOther', function() {
  return {
    restrict: 'A',
    require: 'ngModel',
    link: function(scope, elm, attrs, ctrl) {

        ctrl.$validators.gtOther = function(modelValue, viewValue) { 
            var other = scope.$eval(attrs['gtOther']);
            var thisValue = parseInt(viewValue);
            return thisValue > other;                        
        };
    }
  };
});

Here's a working plunkr

share

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.