skip to Main Content

I have a form which has input fields that is dynamically built using ng-repeat. How I can validate these fields are greater than another input field. Please look at this sample code.

<html ng-app>
<head>
    <link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/css/bootstrap-combined.min.css" rel="stylesheet">
</head>
<body ng-init="weekDays = ['monday', 'tuesday', 'wednesday','thursday', 'friday', 'saturday','sunday']">
    <h1>Fun with Fields and ngModel</h1>
    <p>days: {{weekDays}}</p>
    <h3>Binding to each element directly:</h3>
    <div ng-repeat="weekday in weekDays">
        Value: {{weekday}}
        {{day='day_'+weekday; ""}}
        <input name="{{day}}" ng-model="val">                         
    </div>
    <div>
      Number to validate : <input name="numToValidate">
    </div>
</body>

I am very new to angularJS and still learning. However I couldn’t able to think through this simple validation. Please help.

2

Answers


  1. You can use html form element with min attribute to check validity

    <input name="{{day}}" ng-model="weekday.val" min="{{numToValidate}}">
    

    you will need seperate model for each of your inputs in your ng-repeat therefore I changed your ng-model with the following

    ng-model="weekday.val"
    

    if you do not want to use form you can check the validity of your value with ng-blur directive (triggered when input loses focus).

    html

    <input name="{{day}}" ng-model="weekday.val" ng-blur="checkValid(weekday.val)">
    

    js

    $scope.checkValid = function(value){
        if(value  > $scope.numToValidate){
            alert("please enter a valid number");
        }
    }
    
    Login or Signup to reply.
  2. Html:

    <form name="form">
        <div ng-repeat="weekday in weekDays">
            Value: {{weekday}}
            {{day='day_'+weekday; ""}}
            <input name="{{day}}" ng-model="val" required>                         
        </div>
        <div>
          Number to validate : <input name="numToValidate" required>
        </div>
    </form>
    

    Script:

    if($scope.form.$valid){
        // You can write your code here what you want to do after validate.
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search