2
votes

I have some simply validation in my range inputs like this:

    <form name="form" novalidate>
    Min: <input type="number" name="min" ng-model="rangemin" ng-pattern="/^[0-9]+$/">
    Max: <input type="number" name="max" ng-model="rangemax" ng-pattern="/^[0-9]+$/">
    </form>

I added the classes ng-valid(green) and ng-invalid(red) in my CSS so that it gets painted correctly and the input gets saved in ng-model variable. And that works fine, but I want to put on some extra validation. If min is greater then max or max is lower than min then the input shouldn't be valid.

How can i achieve this?

I'm new to Angular, I can make directives, controllers etc. but I dont know how to validate both inputs and set the invalid state on them.

3

3 Answers

2
votes

You can use the html attribute min and max and the model values from the fields as follows:

<form name="form" novalidate>
Min: <input type="number" name="min" ng-model="rangemin" ng-pattern="/^[0-9]+$/" max="{{rangemax || 9999}}">
Max: <input type="number" name="max" ng-model="rangemax" ng-pattern="/^[0-9]+$/" min="{{rangemin || 1}}">
</form>

And then your condition to display error messages can be: (form.min.$error.max || form.max.$error.min) && (form.min.$dirty || form.max.$dirty).

0
votes

You can you manually write stuff for the angular form $error object. You can write your own custom validation (by using a directive perhaps) and attach the validation to the controller's $validators property (like in the given example for customer validation).

app.directive('customValidation', function() {
    return {
        require: 'ngModel',
            link: function(scope, elm, attrs, controller) {
                controller.$validators.customValidation = function () {
                     //your validation here
                     return isValid;
                }
    ...

You would just have to use this directive in the HTML like

<form name="form" novalidate>
Min: <input type="number" name="min" ng-model="rangemin" custom-validation ng-pattern="/^[0-9]+$/">
Max: <input type="number" name="max" ng-model="rangemax" custom-validation ng-pattern="/^[0-9]+$/">
</form>

Alternatively, (and this is a bit hacky) you can manually watch and set the $error object manually, like with something like

$scope.$watch('rangemin', function() {
    if ($scope.rangemin > $scope.rangemax)
        $scope.form['rangemin'].$error.customerValidation = true; //an error exists
});
0
votes

I think this a good approach

http://jsfiddle.net/jhebr7z8/

But you need to use those directives

app.directive('ngMin', function () {
app.directive('ngMax', function () {