How to validate AngularJS form input while is using ng-repeat - angularjs

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.

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.
}

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");
}
}

Related

AngularJS - ng-maxlength

I've been through all of similar/relative topics on ng-maxlength on StackOverflow, but still could not find an answer. My problem is the following snippet of code:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<div class="form-group field keywords-input-block">
<label>Keywords</label>
<form name="keywords">
<input class="form-control searchKeywordValidator"
type="text"
placeholder="Enter keywords..."
ng-maxlength="5"
name="keywordInput"
ng-model="vm.jobList.keywords">
<h1 ng-if="!keywords.keywordInput.$valid">The value is too long</h1>
</form>
</div>
The error message, which should be displayed only if the input is invalid, is constantly shown! Any advise on what it the reason for that and how could I get rid of it would be highly appreciated!
All angularjs applications must have a root element in order to allow angularjs to be able to effective on your view. And that is ng-app directive. This directive is to auto-bootstrap an AngularJS application
You must add it somewhere to the root element
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<div class="form-group field keywords-input-block" ng-app="">
<label>Keywords</label>
<form name="keywords">
<input class="form-control searchKeywordValidator"
type="text"
placeholder="Enter keywords..."
ng-maxlength="5"
name="keywordInput"
ng-model="vm.jobList.keywords">
<h1 ng-if="!keywords.keywordInput.$valid">The value is too long</h1>
</form>
</div>
Read more about it here

Detect if user changed inputbox in input form with angular?

I want to be able to detect when a field is changed. My form fields are generated using ng-repeat.
Assume formfields is as follows: {"FIELD1":"", "FIELD2":"", "FIELD3":"Prepopulated", "FIELD4":""}
<div ng-controller="MyController">
<form name="myform">
<div ng-repeat="(key, keyvalue) in formfields">
<input name="{{key}}" ng-model="formfields[key]">
</div>
</form>
</div>
My problem is, when I try to log with "console.log($scope.myForm.FIELD1)" inside of my checkPristine() function, pristine is always set to true and never changes to false. How can I check to see if fields have changed? Open to alternatives to pristine if it does not work.
You could add an ng-blur directive to the input like this:
https://jsfiddle.net/54r4991j/
Angular
vm.formfields = {"FIELD1":"", "FIELD2":"", "FIELD3":"Prepopulated", "FIELD4":""};
vm.watchFormField = function(fieldKey) {
alert(fieldKey + 'changed to ' + vm.formfields[fieldKey]);
}
HTML
<form name="myform">
<div ng-repeat="(key, keyvalue) in ctrl.formfields">
<input name="{{key}}" ng-model="ctrl.formfields[key]" ng-blur="ctrl.watchFormField(key)">
</div>
</form>

angular validation - ng-dirty and required is not showing

i have a small angular validation where i want an error to show if a textfield is dirty and another error if it is required.
my html:
<form name="someform1" controller="validateCtrl" novalidate>
<input ng-model="namefld" type="text" required/>
<span ng-show="someform1.namefld.$dirty">pls enter name field</span>
<span ng-show="someform1.namefld.$error.required">Username is required.</span>
</form>
i have set the controller like this:
var myapp = angular.module("myApp",[]);
app.controller('validateCtrl', function($scope) {
$scope.namefld = 'John Doe';
$scope.email = 'john.doe#gmail.com';
});
"myApp" is defined in the <html> tag so that is not the problem. I am missing something and am new to angular, pls guide what i am doing wrong.
You need to add a name to the input too. As you have it set up now $dirty will only work on the form itself not on each individual input, you need to add a name to the inputs for that
Working Demo
You are missing name='namefld'
<input ng-model="namefld" name='namefld' type="text" required/>
Angular form validation works based on the name of the form and the form inputs. In your case you have specified the name of the form but not the input element. Add the name="namefld" to the input element and it will work.
<form name="someform1" novalidate>
<input ng-model="namefld" name="namefld" type="text" required/>
<span ng-show="someform1.namefld.$dirty">pls enter name field</span>
<span ng-show="someform1.namefld.$error.required">Username is required.</span>
</form>
See a working JSbin for same, that I have created

Angular validator, pass data along with error code to be displayed in ngMessages

Is that possible to store some additional data along with the error flag itself, using standard Angular mechanism?
i.e. I'm manually setting ngModel.$setValidity, I'd like to pass some data along with the error flag, to be displayed in ngMessages directive.
For example let's assume the min/max length of the field depends upon some external factors, thus is computed & validated server-side. The server respons with customlength error code along with max and min properties, which I'd like to display to the user.
Currently I'm simply setting ngModel.$setValidity("customlength", false); but I'd like to pass {max: response.max, min: response.min} along, to be interpolated in the template like <div ng-message="customlength">the length should be between {{ data.min }} and {{ data.max }}
I'd like to pass {max: response.max, min: response.min} along, to be interpolated in the template like the length should be between {{ data.min }} and {{ data.max }}
Use the root scope to store the value(s) intended to be output within the message string:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular-messages.js"></script>
<script>
angular.module('ngMessagesExample',['ngMessages']);
</script>
<body ng-app="ngMessagesExample">
<form name="myForm" id="{{$root.$id}}">
<label>
<p>Enter Min:<input type="text" ng-model="form_min">
<p>Enter Max:<input type="text" ng-model="form_max">
<p>Enter your name:
<input type="text"
name="myName"
ng-model="name"
ng-minlength="form_min"
ng-maxlength="form_max"
required />
</label>
<p>
<input type="radio" required name="foo" ng-model="foo" value="1">Yes
<input type="radio" required name="foo" ng-model="foo" value="2">No
</p>
<p>
Foo: <input type="text" ng-model="myForm.foo.$modelValue">
</p>
<p>
<input type="submit" value="{{myForm.foo.$error.required ? 'No' : 'Yes'}}">
</p>
<pre>myForm.myName.$error = {{ myForm.myName.$error | json }}</pre>
<div ng-messages="myForm.foo.$error" style="color:maroon" role="alert">
<div ng-message="required">Pick one</div>
</div>
<div ng-messages="myForm.myName.$error" style="color:maroon" role="alert">
<div ng-message="required">Your value should be between {{form_min}} and {{form_max}} characters long</div>
<div ng-message="minlength" id="{{$id}}">Your value is less than {{form_min}}</div>
<div ng-message="maxlength" id="{{$id}}">Your value is greater than {{form_max}}</div>
</div>
</form>
</body>
References
Easy Form Validation in AngularJS with ngMessages — SitePoint
AngularJS: Developer Guide: Migrating from Previous Versions
Explicitly providing ng-model to DOM elements | TO THE NEW Blog
Using NgModelController with Custom Directives

How to populate a text box using ng-bind?

I'm new to AngularJS and I am going through this link and I am curious to do the experiment on a text box control using ng-bind. But it is not working.
<html>
<title>AngularJS First Application</title>
<body>
<h1>Sample Application</h1>
<div ng-app="">
<p>Enter your Name: <input type="text" ng-model="name"></p>
<input type ="text" ng-bind="name" />
</div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</body>
</html>
How can I populate a text box using ng-bind?
As, The ngBind attribute tells Angular to replace the text content of the specified HTML element with the value of a given expression, and to update the text content when the value of that expression changes, you will not be able to bind to an input box:
<input type ="text" ng-bind="name" />
You can instead use ng-value
<input type="text" ng-value="name" />
or you can populate your input box using the model within the value attribute.
<input type="text" value="{{name}}" />
See this codepen

Resources