3

Having an input

<div ng-app="myApp" ng-controller="myCtrl">
    <form>
        <input type="number" ng-model="$ctrl.myNumber" />
    </form>
</div> 

I want it to be valid, if the input value is any number contained in an array (in this example the array possibleInputValues).

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    var self = this;
    self.possibleInputValues = [1, 2, 3, 4, 7, 8, 9, 10];
});

So, for example, if the user types '2' into the input, it should be valid (as the array possibleInputValues contains 2), but should be invalid eg for the value 5.

One way i found in the AngularJS Documentation is to write a own directive for this kind of validation. Is this the only way or is there a more lightweighted way to do so?

What I am looking for is something like this

<input type="number" ng-model="$ctrl.myNumber" valid-if="$ctrl.isInMyArray()"/>

and the controller

app.controller('myCtrl', function($scope) {
    var self = this;
    self.possibleInputValues = [1, 2, 3, 4, 7, 8, 9, 10];
    self.isInMyArray = function(val) {
        if (self.possibleInputValues.indexOf(val) !== -1) {
            return true
        } 
        return false;
    }
});
3
  • 1
    Take a look at Angular-UI's project that includes a ui-validate directive. It may help you a lot with custom validation. Commented Jun 14, 2017 at 8:37
  • angular-ui/ui-validate lookes like it is exactly what I was looking for. Thanks a lot! Commented Jun 14, 2017 at 8:59
  • Glad to help! I will make it an answer as it helped you. Commented Jun 16, 2017 at 21:41

1 Answer 1

2

Check Angular-UI's project which includes ui-validate/ui-validate-async directives.

This directives makes it very easy to create custom validator expressions. In your case it can look like ui-validate="{inArray: 'isInMyArray($value)' }".

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

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.