i repeated array of input by ng-repeat and want to validate by angular.
my input form is such as this. How validate array of inputs.
thanks.
<div ng-repeat="item in items track by $index">
<input name = "apartment.home[$index].name" ng-model='item.name' required>
<span ng-show="apartment.home[$index].name.$error.required">
name is required.</span>
<input name = "apartment.home[$index].phone" ng-model='item.phone'>
</div>
There is an example for the usage. Here is the list:
<input
ng-model="string"
[name="string"]
[required="string"]
[ng-required="boolean"]
[ng-minlength="number"]
[ng-maxlength="number"]
[ng-pattern="string"]
[ng-change="string"]
[ng-trim="boolean"]>
...
</input>
And here is an example:
<script>
angular.module('inputExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.user = {name: 'guest', last: 'visitor'};
}]);
</script>
<div ng-controller="ExampleController">
<form name="myForm">
<label>
User name:
<input type="text" name="userName" ng-model="user.name" required>
</label>
<div role="alert">
<span class="error" ng-show="myForm.userName.$error.required">
Required!</span>
</div>
<label>
Last name:
<input type="text" name="lastName" ng-model="user.last"
ng-minlength="3" ng-maxlength="10">
</label>
<div role="alert">
<span class="error" ng-show="myForm.lastName.$error.minlength">
Too short!</span>
<span class="error" ng-show="myForm.lastName.$error.maxlength">
Too long!</span>
</div>
</form>
<hr>
<tt>user = {{user}}</tt><br/>
<tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br/>
<tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br/>
<tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br/>
<tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
<tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br/>
<tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br/>
</div>
and a .js example:
var user = element(by.exactBinding('user'));
var userNameValid = element(by.binding('myForm.userName.$valid'));
var lastNameValid = element(by.binding('myForm.lastName.$valid'));
var lastNameError = element(by.binding('myForm.lastName.$error'));
var formValid = element(by.binding('myForm.$valid'));
var userNameInput = element(by.model('user.name'));
var userLastInput = element(by.model('user.last'));
it('should initialize to model', function() {
expect(user.getText()).toContain('{"name":"guest","last":"visitor"}');
expect(userNameValid.getText()).toContain('true');
expect(formValid.getText()).toContain('true');
});
it('should be invalid if empty when required', function() {
userNameInput.clear();
userNameInput.sendKeys('');
expect(user.getText()).toContain('{"last":"visitor"}');
expect(userNameValid.getText()).toContain('false');
expect(formValid.getText()).toContain('false');
});
it('should be valid if empty when min length is set', function() {
userLastInput.clear();
userLastInput.sendKeys('');
expect(user.getText()).toContain('{"name":"guest","last":""}');
expect(lastNameValid.getText()).toContain('true');
expect(formValid.getText()).toContain('true');
});
it('should be invalid if less than required min length', function() {
userLastInput.clear();
userLastInput.sendKeys('xx');
expect(user.getText()).toContain('{"name":"guest"}');
expect(lastNameValid.getText()).toContain('false');
expect(lastNameError.getText()).toContain('minlength');
expect(formValid.getText()).toContain('false');
});
it('should be invalid if longer than max length', function() {
userLastInput.clear();
userLastInput.sendKeys('some ridiculously long name');
expect(user.getText()).toContain('{"name":"guest"}');
expect(lastNameValid.getText()).toContain('false');
expect(lastNameError.getText()).toContain('maxlength');
expect(formValid.getText()).toContain('false');
});
All taken from angularjs.org documentation.
Related
I have used the error form validation in the addnewstudent page as below and it's working fine.
<td>
<input limit-to="50" type="email" name="input" ng-model="Email" />
<span style="display:none">{{ emailValid = !!myForm.$error.email}}</span>
<span ng-class="customStyle.colorClass">
{{EmailValidation }}
</span>
</td>
Same approach I used for my edit page as like below, but Iam not able to get the bool value of "!!myForm.$error".
my Edit page
<td>
<input limit-to="50" type="text" ng-model="Student.email" />
<span style="display:none">{{ emailValid = !!myForm.$error.Student.email}}
</span>
<span>
{{EmailValidation }}
</span>
</td>
My JS,
$scope.save = function () {
if ($scope.emailValid || $scope.Student.email=='') {
$scope.EmailValidation = 'Not a valid email (ex: me#example.com)';
return;
}
else {
$scope.EmailValidation = '';
}
.......
.......
Where I did go wrong on my edit page?
To validate a form input in angularjs there should be name attribute for that input and form also.
angular.module('sampleApp', [])
.controller('myCtrl', function($scope) {
$scope.Student = {}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="sampleApp" ng-controller="myCtrl" >
<form name="myForm" novalidate>
<input limit-to="50" type="email" ng-model="Student.email" name="email" required/>
<div ng-show="myForm.$submitted || myForm.email.$touched">
<span ng-show="myForm.email.$error.required">Tell us your email.</span>
<span ng-show="myForm.email.$error.email">This is not a valid email.</span>
</div>
<button>Submit</button>
</form>
</div>
Above code will check for non empty valid email, which is done by required,type="email" attributes.
I've this code:
<div class="row" ng-repeat="input in inputs | filter:inputNumber">
<ng-form name="form1">
<div class="col-xs-3">
<div class="form-group">
<input ng-model="inputs.number[$index]" type="number" name="number$index" class="form-control" placeholder="" min="1" max="9999" required />
<small class="label label-danger" data-ng-show="submitted && form1.number$index.$error.required">required</small>
<small class="label label-danger" data-ng-show="submitted && form1.number$index.$error.number">number</small>
<small class="label label-danger" data-ng-show="submitted && form1.number$index.$error.max">number max</small>
</div>
</div>
</ng-form>
</div>
<button data-ng-click="add(form1)" class="btn-add" style="padding-left: 40%;"></button>
Controller:
// Form add handler.
$scope.add = function(form) {
// Trigger validation flag.
$scope.submitted = true;
// If form is invalid, return and let AngularJS show validation errors.
if (form.$invalid) {
console.log('invalid');
return;
} else {
var newItemNo = $scope.inputs.length + 1;
var inputs = { 'id': 'input' + newItemNo }
$scope.inputs.push(inputs);
$scope.isDisabled = false;
}
};
The problem is I can only validate the form inputs inside ng-repeat and ng-form, and I need to trigger the event outside of that html block, maybe I'm just being noob (first time using angular1 validations). I will appreciate some help. Thanks in advance.
Based on you comment and following the same goal of generating a form for each element in your ng-repeat, this should be the answer:
html
<form name="generalForm"> <!-- this form will be valid if all sub-forms are valid-->
<div class="row" ng-repeat="input in inputs | filter:inputNumber">
<ng-form name="form1">
<div class="col-xs-3">
<div class="form-group">
<input ng-model="inputs.number[$index]" type="number" name="number$index" class="form-control" placeholder="" min="1" max="9999" required />
<small class="label label-danger" data-ng-show="submitted && form1.number$index.$error.required">required</small>
<small class="label label-danger" data-ng-show="submitted && form1.number$index.$error.number">number</small>
<small class="label label-danger" data-ng-show="submitted && form1.number$index.$error.max">number max</small>
</div>
</div>
</ng-form>
</div>
<button data-ng-click="add(generalForm)" class="btn-add" style="padding-left: 40%;"></button>
</form>
controller
// Form add handler.
$scope.add = function(form) {
// Trigger validation flag.
$scope.submitted = true;
// If form is invalid, return and let AngularJS show validation errors.
if (form.$invalid) {
console.log('invalid');
return;
} else {
var newItemNo = $scope.inputs.length + 1;
var inputs = { 'id': 'input' + newItemNo }
$scope.inputs.push(inputs);
$scope.isDisabled = false;
}
};
https://jsfiddle.net/jzhang172/xu93yubL/
The particular issue is in my E-mail input field.
Is it possible to only display the ng-show message after the field is validated and when the user is not inside the input field?
In other words, I want the ng-show message to disappear if the user is on the input field.
I've tried a number of combinations of logic and haven't been able to get it to work:
(function(angular) {
'use strict';
angular.module('formExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.master = {};
$scope.update = function(user) {
$scope.master = angular.copy(user);
};
$scope.reset = function(form) {
if (form) {
form.$setPristine();
form.$setUntouched();
}
$scope.user = angular.copy($scope.master);
};
$scope.reset();
}]);
})(window.angular);
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<body ng-app="formExample">
<div ng-controller="ExampleController">
<form name="form" class="css-form" novalidate>
Name:
<input type="text" ng-model="user.name" name="uName" required="" />
<br />
<div ng-show="form.$submitted || form.uName.$touched">
<div ng-show="form.uName.$error.required">Tell us your name.</div>
</div>
E-mail:
<input type="email" ng-model="user.email" name="uEmail" required="" />
<br />
<div ng-show="form.$submitted || form.uEmail.$touched">
<span ng-show="form.uEmail.$error.required" style="background:red;">Tell us your email.</span>
<span ng-show="form.uEmail.$error.email"style="background:red;">This is not a valid email.</span>
</div>
</form>
</div>
</body>
You can use ngFocus and ngBlur directives to achieve desired result...
Just set some variable false on ngFocus and set true with ngBlur and add that variable into your ngShow condition...
<input type="email" ng-model="user.email" name="uEmail" required="" ng-focus="showEmailValidationMsg = false;" ng-blur="showEmailValidationMsg = true;"/>
<br />
<div ng-show="(form.$submitted || form.uEmail.$touched) && showEmailValidationMsg">
<span ng-show="form.uEmail.$error.required" style="background:red;">Tell us your email.</span>
<span ng-show="form.uEmail.$error.email"style="background:red;">This is not a valid email.</span>
</div>
and here is working JSFIDDLE...
I need to generate form input fields dynamically by clicking 'add sale' button on the form. which is accomplished
Also on change selected drop down, it get the price from the database and use the quantity to calculate the amount of that product.
if I click on 'add sale' button for another form generate the changes affect the previous one.
how to calculate the amount for each form independently and collect the data in it using angularJS?
this is controller
appcat.controller("MainCtrl", ['$scope', '$http', '$location', function ($scope, $http, $location)
{
//var quan = $scope.quantity;
$http.get('/api/pproduct').success(function (data)
{
$scope.pcategoryA = data;
});
// this controll the addition and removal
$scope.choices = [{ id: 'choice1' }];
//any time changes occurr it calculate the Amount
$scope.changedValue = function (item,quan)
{
if (item != null && quan !=null)
{
$http.get('/api/product/'+ item).success(function (data) // this is the price for that product from the Database
{
//this sets amount field
$scope.amount = parseFloat(data.price * quan);
});
}
}
// this generate a form
$scope.addNewChoice = function ()
{
var newItemNo = $scope.choices.length + 1;
$scope.choices.push({ 'id': 'choice' + newItemNo });
};
// this remove the form
$scope.removeChoice = function () {
var lastItem = $scope.choices.length - 1;
if ($scope.choices.length > 1) {
$scope.choices.splice(lastItem);
}
};
}]);
this is the html
<form class="form-inline" role="form" padding-left:10em">
<strong class="error">{{ error }}</strong>
<div class="form-group">
<label for="name">
Invoice No. :
</label>
<input type="text" class="form-control" id="name" ng-model="name" />
</div>
<br /><hr />
<div ng-controller="MainCtrl">
<fieldset data-ng-repeat="choice in choices">
<div class="form-group">
<label for="name">
Quantity :
</label>
<input type="text" class="form-control" id="quantity" ng-model="quantity" />
</div>
<div class="form-group">
<div class="form-group">
<label class="control-label"> Product : </label>
<select class="form-control" id="selected_id" ng-model="selected_id" ng-options="c.Value as c.Text for c in pcategoryA"
ng-change="changedValue(selected_id,quantity)">
<option value="">-- Select Category --</option>
</select>
</div>
</div>
<div class="form-group">
<label for="name">
Amount :
</label>
<input type="text" class="form-control" id="amount" ng-model="amount" ng-readonly="true" />
</div>
<button class="remove" ng-show="$last" ng-click="removeChoice()">-</button>
<br />
<hr />
</fieldset>
<button type="submit" class="col-sm-offset-10 addfields" ng-click="addNewChoice()">
Add Sale
</button>
</div>
</form>
thanks in advanced!!
You have to put 'amount' in choices array.
$scope.choices = [{ id: 'choice1', amount: 0}];
Then in controller:
$scope.changedValue = function (choise,item,quan)
choise.amount = parseFloat(data.price * quan);
And in tempalte:
ng-change="changedValue(choise,selected_id,quantity)">
<input type="text" class="form-control" id="amount" ng-model="choise.amount" ng-readonly="true" />
I use the angularjs framework, I created an form.html and a controller.js with a variable that retrieves the SSID of a box.
How to automatically assign the value of the variable in the form.
This is an input field.
When launching the application, the form should display the SSID automatically without the user needing to do so.
Thank you kindly help me.
'use strict';
angular.module('djoro.controllers')
.controller('WifiSmartConfigCtrl', function ($scope, $window, $ionicPlatform) {
$scope.getSSID = function () {
var onSuccess = function (SSID) {
document.write(SSID);
};
var onFail = function () {
};
$ionicPlatform.ready(function () {
$window.cordova.plugins.Smartconfig.getSSID(onSuccess, onFail);
});
};
});
<ion-pane>
<ion-content ng-controller="WifiSmartConfigCtrl">
<form novalidate class="simple-form">
<fieldset>
<legend>WI-FI</legend>
<div class="list input-fields">
<label class="item item-input">
<span class="input-label">SSID :</span>
<input type="text" name="test" value="getSSID()" required show-hide-input>
</label>
<label class="item item-input" show-hide-container>
<span class="input-label">Password :</span>
<input type="text" name="password" required show-hide-input>
</label>
</div>
</fieldset>
</form>
</ion-content>
</ion-pane>
use the ng-model directive, it's exactly it's purpose :
'use strict';
angular.module('djoro.controllers')
.controller('WifiSmartConfigCtrl', function($scope, $window, $ionicPlatform) {
$scope.SSID = {};
$scope.getSSID = function() {
var onSuccess = function(SSID) {
$scope.SSID = SSID;
};
var onFail = function() {};
$ionicPlatform.ready(function() {
$window.cordova.plugins.Smartconfig.getSSID(onSuccess, onFail);
});
};
});
and in your view :
<input type="text" name="test" ng-model="SSID" required show-hide-input>
You need to add an ng-model to the input field like so:
<label class="item item-input">
<span class="input-label">SSID :</span>
<input type="text" name="test" ng-model="SSID" required show-hide-input>
</label>
then in your controller assign the value of SSID on the $scope:
$scope.SSID = [some_value]
see this plnkr
As you can see I have assigned the value of SSID manually, you can add it dynamically by assigning it in the callback of your function like so:
$scope.SSID = {}
var onSuccess = function (SSID) {
document.write(SSID);
$scope.SSID = SSID
};