Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angularJs - Custom validation rules for form

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?

like image 925
Jordumus Avatar asked Jun 28 '26 07:06

Jordumus


2 Answers

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

like image 147
Yaron Schwimmer Avatar answered Jul 01 '26 21:07

Yaron Schwimmer


for field2 valid use:

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

for field3 use:

<input type="number" ng-required="field2>0">
like image 34
user3227295 Avatar answered Jul 01 '26 19:07

user3227295



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!