Server side validation for multiple fields in Angular - angularjs

I have form where I need validation on server side. Backend use one request to validate multiple fields.
I try to add validation message after response. Here is example:
This is my html code:
<div ng-app="MyApp">
<div ng-controller="MyController">
<form name="MyForm" novalidate ng-submit="send()">
<div>
<label>Email</label>
<input type="email" name="email" ng-model="user.email" required>
<div ng-show="MyForm.email.$invalid">error message</div>
</div>
<input type="submit" ng-disabled="MyForm.$invalid">
<pre>{{ MyForm.email.$error | json }}</pre>
</form>
</div>
</div>
And my js code:
var myApp = angular.module('MyApp', []);
myApp.controller("MyController", ['$scope', '$timeout', '$log', function($scope, $timeout, $log) {
$scope.user = { "email" : "" }
$scope.send = function() {
$timeout(function() {
$log.log("Response from server. Multiple fields validation.");
$scope.MyForm["email"].$setValidity("server-side-error", false, $scope.MyForm)
// here I want to add something what listen once on $scope.MyForm["email"] changed
}, 1000);
};
}]);
But I need remove error when value changed. How to achieve it using Angular?
Here is example: https://jsfiddle.net/9wqhd89z/

You can call a check function whenever the user change the input using ng-change. So it will check if the email is currently invalid, and if it is it will set as valid again.
<input type="email" name="email" ng-model="user.email" ng-change="check()" required>
$scope.check = function(){
if ($scope.MyForm.email.$valid == false){
$scope.MyForm.email.$setValidity('server-side-error', true);
}
}
You can find a working version in this jsFiddle

Related

How to detect focus on Angular 1

I am having multiple input text in form and on ng-focus I am calling a method let's say GetFieldName().
I my angular.js how can I detect that method having the focus on first field or second.
How can I validate that withing getFieldName() method to get field which have focus on it.
The best solution is to make angularJS directive to get the attrs
or to make the validation
https://docs.angularjs.org/guide/forms
This is solution with controller and $event to get the name attribute from element
var myApp = angular.module('myApp',[]);
myApp.controller('formCtrl', ['$scope', function($scope) {
$scope.text = "sample text";
$scope.getName = function(event){
$scope.text = event.target.getAttribute('name');
};
}]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myApp">
<form ng-controller="formCtrl">
{{text }}
<input type="text" name="text1" ng-focus="getName($event)">
<input type="text" name="text2" ng-focus="getName($event)">
<input type="text" name="text3" ng-focus="getName($event)">
<input type="text" name="text4" ng-focus="getName($event)">
</form>
</div>

angular removes ng-model variable if ng-required is true

as in the title.. how to prevent such operations to happen? Here is a link to the official site, see the example. The variable user.name is bound to the first input userName and if the input is empty the object user.name is removed. How can I disable this functionality of angularjs?
Try ng-model-options="{allowInvalid: true}" to update the model even for invalid entries.
<input ng-model="user.name" required ng-model-options="{allowInvalid: true}">
You've got 2 option
remove required from input tag it allows you to send back empty string to your backend
var app = angular.module('app', []);
app.controller('MyCtrl', function($scope) {
$scope.params = {
user: "John"
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="MyCtrl">
<input name="userName" ng-model="params.user" />
<hr/>
<pre>{{params| json}}</pre>
</div>
Option two validate your form before you send it to backend.
var app = angular.module('app', []);
app.controller('MyCtrl', function($scope) {
$scope.user = {
name: "John"
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="MyCtrl">
<form name="someForm">
<input name="userName" ng-model="user.name" required name="userName" />
<span ng-show="someForm.userName.$error.required">User Name required</span>
<br/>{{user | json}}
<br/>
<button type="submit" ng-disabled="someForm.$invalid">Submit</button>
</form>
</div>

Cannot read property $valid of undefined

I have a form like this -
<form name="myForm" novalidate>
There are some fields in the form which I am validating and then submitting the form like this -
<input type="button" ng-click="Save(data)" value="Save">
In the controller, I want to check if the form is not valid then Save() should show some error on the page. For that, I am setting up a watch like this -
$scope.$watch('myForm.$valid', function(validity) {
if(validity == false)
// show errors
});
But I am always getting this error on running it -
Cannot read property '$valid' of undefined
Can someone explain why?
Thanks
You just misspelled "myForm" in your controller code. In order to remove the error, Write "myform" instead of "myForm".
However I expect what you want is like this.
$scope.Save = function(data){
alert($scope.myform.$valid);
}
I setup jsfiddle.
In my case I was wrapping the form in a modal created in the controller and therefore got the same error. I fixed it with:
HTML
<form name="form.editAddress" ng-submit="save()">
<div class="form-group">
<label for="street">Street</label>
<input name="street" type="text" class="form-control" id="street" placeholder="Street..." ng-model="Address.Street" required ng-minlength="2" />
<div class="error" ng-show="form.editAddress.street.$invalid">
<!-- errors... -->
</div>
</div>
<button type="submit" class="btn btn-primary" >Save address</button>
</form>
JS
angular.module("app").controller("addressController", function ($scope, $uibModal, service) {
$scope.Address = {};
$scope.form = {};
$scope.save = function() {
if (modalInstance !== null) {
if (isValidForm()) {
modalInstance.close($scope.Address);
}
}
};
var isValidForm = function () {
return $scope.form.editAddress.$valid;
}
});

firebaseSimpleLogin: $createUser Promise Not Resolving until Another Event Occurs

I'm setting up registration/login functionality using angular, Firebase, and firebaseSimpleLogin. After reading over a few tutorials and another Stack Overflow thread, I've got the registration working with one small but important caveat: the promise on the SimpleLogin $createUser function isn't resolving until I click on a link or button on my html page. Here's my code:
Register.html
<div class="form-group" >
<label class="control-label" for="email">Email</label>
<input class="form-control" type="text" name="email" id="email" ng-model="cred.email"/>
<label class="control-label" for="password">Password</label>
<div class="form-group">
<input class="form-control" type="password" name="password" id="password" ng-model="cred.password"/>
</div>
<div class="form-group">
<input type="submit" value="Register" class="btn btn-primary" ng-click="register()"/>
</div>
</div>
Main.Js
angular.module('myApp')
.controller('AuthCtrl',
['$scope',
'$location',
'$firebase',
'$firebaseSimpleLogin',
'loginService',
function AuthCtrl($scope, $location, $firebase, $firebaseSimpleLogin,
loginService) {
$scope.register = function(){
var user = {
email: $scope.cred.email,
password: $scope.cred.password
};
loginService.register(user);
};
});
loginService.js (note FBURL is defined elsewhere)
angular.module('myApp')
.factory('loginService', function($firebaseSimpleLogin, $rootScope, $location,
$timeout) {
var ref = new Firebase(FBURL);
var auth = $firebaseSimpleLogin(ref);
return {
register: function (user) {
return auth.$createUser(user.email, user.password)
.then(function(registeredUser) {
console.log(registeredUser);
}
)}
});
In the above loginService.js, I'm not seeing the console.log until I click a button or element; however, the user is created in the Firebase Simple Login DB when I look online. As soon as I click a button or element, the console.log shows. My guess as to the issue is that the promise from auth.$createUser() isn't getting resolved, but I cannot find out why that would be.

How to get data from ngform in angularjs?

HTML:
<div ng-controller="TestController" >
<form name="test_form" ng-submit="submit()">
<input type="text" name="some_name" ng-model="form_data.some_name" required>
<ng-form ng-repeat="key in keys" name="keyForm">
<input type="text" name="data_input" ng-model="form_data.data_input" required>
</ng-form>
<a ng-click="addKey()">NEW KEY</a>
</form>
</div>
JS:
app.controller('TestController', function TestController($scope){
$scope.keys = [];
$scope.addKey = function() {
$scope.keys.push({});
}
$scope.submit = function() {
console.log($scope);
}
});
In submit function I can get the value of "some_name" input:
$scope.submit = function() {
console.log($scope.form_data.some_name);
}
But I can't get the values of "data_input" inputs (they are inside ngform tag). How to do that?
(ngform tag is using for ability to validate each new added input separately)
Each input inside the ng-repeat needs its own unique ng-model property -- they all can't use form_data.data_input. Here is one way to solve your problem:
<ng-form ng-repeat="key in keys" name="keyForm">
<input type="text" name="data_input" ng-model="key.data" required>
</ng-form>
$scope.addKey = function () {
$scope.keys.push({ data: ''});
}
Fiddle.
See also https://stackoverflow.com/a/14379763/215945

Resources