I'm trying to implement validation for a form using Angular 1.1.1 and Ionic.
There are many "wallets" and the user needs to send a new "value" to each of the wallet. There's also a specified previous value of the wallet. The validation should check if all the input field are filled out and if the new value is bigger than previous.
My form (index.html):
<form name="myForm" ng-submit="sendValues(wallets)" ng-controller="valuesCtrl">
<div class="row" ng-repeat="wallet in wallets">
<div class="col item item-input-inset">
<label class="item-input-wrapper item-text-wrap">
<input name="wallet_{{wallet.id}}" type="number" ng-model="wallet.value" type="text" required/>
</label>
<span ng-show="myForm.wallet_{{item.id}}.$error.required">!!!</span>
</div>
<div class="col item">{{ wallet.previous }}</div>
</div>
<button class="button" type="submit">Submit</button>
</form>
It results in always showing "!!!" error for empty input even if the user haven't already submitted the form. I tried to use $scope.myForm.submitted=true; in the controller but the problem is it reaches the controller only if all the fields are filled out.
My controller (values.js):
'Use Strict';
angular.module('App')
.controller('valuesCtrl', function($scope, $localStorage, UserService, $state) {
$scope.sendValues = function(wallets){
debugger;
...
})
Can anyone help me to figure out why I can't see the debugger window if not all the fields are with info?
Can you suggest how to make a custom validation? (new value should be bigger than previous)
It results in always showing "!!!" error for empty input even if the user haven't already submitted the form?
Your ng-show should be
ng-show="myForm.$submitted==true && myForm.wallet_{{item.id}}.$error.required"
and form should be have novalidate attribute if you want custom validation
<form name="myForm" ng-submit="sendValues(wallets)" novalidate>
otherwise it will do default html validation
I tried to use $scope.myForm.submitted=true; in the controller but the problem is it reaches the controller only if all the fields are filled out
Its because ng-submit will validate for true condition($valid==true) for every form control element .
If it is filled and valid data then only form $valid flag is set to true otherwise not.In case $valid==true,you will able to submit the form and function in controller get fired
you can use
<input type="submit" ng-click="sendValues(wallets)" value="Save" />
if you want to submit the form without validation and want to do validation in controller
You can read more from angular#form
Related
So I've recently taken over an Angular Giving Form Application. I am running validation on the email field using ng-pattern and displaying the errors on blur with ngMessages. The validation works great, however once the validation passes as $valid if the user decides they need to make a change in their email and begin to delete part of the first deletion deletes the last character of the email as expected, but the second deletion deletes the entire field forcing the user to start from scratch.
The regex for ng-pattern is being set in the controller scope with the variable $scope.emailre
The files are much to large to place here but here is the link to the site I am working on for my client.
https://epiqa.moodyglobal.org/corporate/
Snippet of Angular controller:
myApp.controller('mainCtrl', function($scope, localStorageService, $http) {
$scope.emailre = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
Snippet of HTML Form:
<div class="row form-group">
<div class="col-sm-6">
<div>
<label class="label" for="txt_donorEmail">E-mail:</label>
<input ng-class="{ 'submitted-error' : givingForm.email.$invalid && submitted }" ng-model="email" type="text" id="email" name="email" class="textbox required full form-control" maxlength="50" ng-pattern="emailre" required />
</div>
<div ng-messages="givingForm.email.$error" ng-if="givingForm.email.$touched || submitted">
<div class="errorText" ng-message="required">This field is required</div>
<div class="errorText" ng-message="pattern">Enter a valid email</div>
</div>
</div>
</div>
I have tried changing the input type from type="text" to type="email" but when doing that any time the user types two (.) periods the field gets immediately deleted.
Please help any ideas are very welcome.
The behavior is caused by this section
$scope.$watch('email', function(value){
localStorageService.set('email',value);
$scope.emailValue = localStorageService.get('email');
});
By Angular documentation
The default behaviour in ngModel is that the model value is set to undefined when the validation determines that the value is invalid. By setting the allowInvalid property to true, the model will still be updated even if the value is invalid.
I'm not sure whether you want to save the invalid email into localStorage, though. Maybe you can add a check only update when the value is valid.
In Angularjs 1 there are many examples of validation on submit OR on user input.
In this project I need to update the validation messages on user clicks submit button only, i.e, the USER INPUT WILL NOT UPDATE THE VALIDATION MESSAGES (client spec).
Example: http://embed.plnkr.co/N0rRBS8AXU3jQJjQidIT/
It seems you only need validation on the controller, so to turn off html validation you need novalidate like this in your html:
<form name="yourForm" ng-controller="YourController as yourCtrl" ng-submit="yourCtrl.yourmethod(data)" novalidate>
then you proceed to do your validations in your controller
Here is my option:
(function(){
'use strict';
var app = angular.module('sample', []);
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="sample">
<form name="userRegister" novalidation>
<div ng-messages="userRegister.name.$error.required"
ng-if="submitted ">
<p ng-message="required">I need your name Sr</p>
</div>
<input type="text" ng-required name="name" ng-model="user.name">
<input value="Send" type="submit" ng-click="submitted=true"/>
</form>
</div>
I'm creating a modal dialog and trying to read the fields back when the dialog is closed, but when the input is edited, the ng-model for the input field is being set to undefined. With the Plunk, if you click the dialog button and then press Ok without modifying the text field, it will display "blah". But if you modify the text input at all, then nothing will be displayed.
The dialog template is:
<script type="text/ng-template" id="simpleModal.html">
<div class="modal-header">
<h3 class="modal-title">Simple Modal</h3>
</div>
<div class="modal-body">
<div class="form-group">
<label for="emailInput">Email</label>
<input id="emailInput" type="email" class="form-control" ng-model="user.email">
</div>
</div>
<div class="modal-footer">
<button class="btn" type="button" ng-click="ok()">Ok</button>
</div>
</script>
And the controller for the modal dialog:
app.controller('SimpleModalController', function($scope, $uibModalInstance, $log) {
$scope.user = {
email: "blah"
};
$scope.ok = function() {
$log.debug('simpleModal ok called ' + $scope.user.email);
$uibModalInstance.close($scope.user.email);
};
});
I've seen reference to https://stackoverflow.com/a/22768720/552936, but I've changed my code to reflect this and it hasn't fixed the issue.
You have declared input type="email" in your input field in modal
<input id="emailInput" type="email" class="form-control" ng-model="user.email">
It'll pass value if data according to email . like a#b.com
You can check if data has valid email
HTML
<form name="myForm">
<input type="email" name="myEmail" model="myEmail" />
<span>Valid Email {{myForm.myInput.$valid}}
</form>
PLUNKR
If you wanna pass any string then you have to make it type="text".
The reason it's being set to undefined is because you have the input for the email address as type=email. If you put anything but a valid email address in that field user.email will be set to undefined.
I just ran your plunker and put in a valid email address and can see it's has been set correctly. This is an instance where you should be validating that it's a well formed email address before allowing submission.
I have a form inside a modal pop up. I am trying to run form validation on the inputs after the user attempts to submit the form. So far, I'm struggling to make things work.
In my view, I have the following (sorry if there are any syntax errors, I'm converting this from jade on the fly):
<script type="text/ng-template", id="modalVideoNew">
<div class="ngdialog-message">
<form class="form-horizontal" ng-submit="submitForm()" novalidate name="newVideoForm">
...
<div class="form-group">
<label> Title </label>
<div class="col-sm-8">
<input type="text" name="title", required='', ng-model="newVideoForm.title">
<span class="text-danger" ng-show="validateInput('newVideoForm.title', 'required')"> This field is required</span>
</div>
</div>
</div>
</script>
And then in my controller, where I'm calling the ng-dialog pop up, I have this:
$scope.newVideo = function() {
ngDialog.openConfirm({
template: 'modalVideoNew',
className: 'ngdialog-theme-default',
scope: $scope
}).then(function() {
$scope.validateInput = function(name, type) {
var input = $scope.newVideoForm[name];
return (input.$dirty || $scope.submitted) && input.$error[type];
};
var newVideo = $scope.newVideoForm;
...
Right now, I am still able to submit the form, but once I open it back up I see the 'This field is required' error message. Also, the input is pre-filled with [object, Object] instead of an empty text input box.
A way of cleaning your model would work with using a model var that belongs to your parent controller and cleaning it in the callback. Check out how the template has attached your parent controller's var FormData.
Check this out
So about your validation, what I would recommend you is to have your own controller in it, no matter how much code it will have. It helps you keeping concepts of modularization and a better control over your scopes. This way will also facilitate a lot when validating.
I'm wondering why my required messages are not hiding on load when a user first views my form?
My code is as per:
<div ng-messages="loginForm.username.$error" class="form-input-error">
<div class="message" ng-message="required">Please enter your username</div>
<div class="message" ng-message="maxlength">Username is too long.</div>
</div>
The ng-message="maxlength" doesn't appear until the requirement is met however, I don't understand why required is showing on load?
Ideally I would like the required message to display if the user tries to submit the form with none of the fields entered or if only one field has been entered. Essentially, meeting the required validation rules.
Here is a JSFIDDLE example
This is because angular validation will evaluate if the form meets the requirements on load and since there is no value in the required field then it's invalid. As the username is 0 characters it's less than the maxlength so that's valid.
By default for ng-messages angular will only show the first message that is invalid. In this case that is fine.
To prevent messages showing until submit is clicked you can set a scope property on submit and use a ng-show on the ng-messages to only show the validation message if submitted:
$scope.submitForm = function(isValid) {
$scope.submitted = true;
// Check to make sure the form is completely valid
if (isValid) {
alert('Form is valid');
}
};
<form name="loginForm" ng-controller="LoginCtrl" novalidate="novalidate" ng-submit="submitForm(loginForm.$valid)">
<div ng-messages="loginForm.username.$error" class="form-input-error" ng-show="submitted">
<div class="message" ng-message="required">Please enter your username</div>
<div class="message" ng-message="maxlength">Username is too long.</div>
</div>
JsFiddle