3

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?

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

for field2 valid use:

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

for field3 use:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.