angularjs - ngMessages and validation not working as expected - angularjs

I'm adding validation to the user registration page in my app and I'm trying to use ngMessages and the build-in angularjs validation.
I'm experiencing strange behaviour for password matching and with patterns in general.
Here's the code for password matching:
<span>Password (6 to 16 character)</span>
<span class="item item-input">
<input type="password"
ng-model="userRegistration.password"
placeholder="password"
name="password"
ng-minlength="6"
ng-maxlength="16"
required
ng-class="{'invalid-input': userRegistrationForm.password.$touched && userRegistrationForm.password.$invalid }">
</span>
<!-- Form validation messages -->
<div role="alert" class="error-message" ng-messages="userRegistrationForm.password.$error" ng-show="userRegistrationForm.password.$touched">
<p ng-message="required">This field is required</p>
<p ng-message="minlength">This field is too short</p>
<p ng-message="maxlength">This field is too long</p>
</div>
<span>Confirm Password</span>
<span class="item item-input">
<input type="password"
placeholder="confirm password"
ng-model="userRegistration.passwordConfirmation"
name="confpass"
ng-minlength="6"
ng-maxlength="16"
ng-pattern="/^{{userRegistration.password}}$/"
required
ng-class="{'invalid-input': userRegistrationForm.confpass.$touched && userRegistrationForm.confpass.$invalid }">
</span>
<!-- Form validation messages -->
<div role="alert" class="error-message" ng-messages="userRegistrationForm.confpass.$error" ng-show="userRegistrationForm.confpass.$touched">
<p ng-message="required">This field is required</p>
<p ng-message="pattern">Password not matching!</p>
</div>
The problem is that even If the password matches, the error stays there displayng that it is not matching and I cannot figure out why is it doing this.
Another example of pattern not behaving as expected can be found in the code below:
<span>System ID</span>
<span class="item item-input">
<input type="text"
ng-model="userRegistration.id"
placeholder="system id"
name="systemID"
ng-minlength="6"
ng-maxlength="6"
pattern="/:/"
required
ng-class="{'invalid-input': userRegistrationForm.systemID.$touched && userRegistrationForm.systemID.$invalid }">
</span>
<!-- Form validation messages -->
<div role="alert" class="error-message" ng-messages="userRegistrationForm.systemID.$error" ng-show="userRegistrationForm.systemID.$touched">
<p ng-message="required">This field is required</p>
<p ng-message="pattern">Colons not required!</p>
<p ng-message="minlength">This field is too short</p>
<p ng-message="maxlength">This field is too long</p>
</div>
I need to check if colons are added in the input, and display and error if they are. The proble, as above, is that even if colons are not there, the message is still displayed.
What am I missing? I'm clearly using ng-pattern and ng-messages wrong, but can't understand why.
Any help would be really appreciated.
Codepen with both examples here: http://codepen.io/NickHG/pen/NNZYwK?editors=1010
Thanks

I used a little different approach to get this to work with ng-messages. I made a custom directive like this:
.directive('compareTo', function() {
return {
require: "ngModel",
scope: {
otherModelValue: "=compareTo"
},
link: function(scope, element, attributes, ngModel) {
ngModel.$validators.compareTo = function(modelValue) {
return modelValue == scope.otherModelValue;
};
scope.$watch("otherModelValue", function() {
ngModel.$validate();
});
}
};
});
And display the error with it like this:
<div role="alert" class="error-message"
ng-messages="userRegistrationForm.conf.$error"
ng-show="userRegistrationForm.conf.$touched">
<p ng-message="required">This field is required</p>
<p ng-message="compareTo">Password not matching!</p>
</div>
For further information and a demo please see the link below.
Codepen demo: http://codepen.io/thepio/pen/rLNBWr?editors=1010
EDIT based on comment:
Here is an example with using ng-pattern (no directive needed): http://codepen.io/thepio/pen/zBYOPy?editors=1010
I set a ng-change function to your first input and set a regexp in the controller when it's changed. Then I bind it to the ng-pattern of the confirmation input and show the ng-messages accordingly.

Related

Resting Form and Clear Error Validations in register form on clicking a button

I am doing one register page using angularjs.
Follows my html code:
<form name="frominline" action="post" class="clearfix form-hidden" id="Register-form">
<div class="col-md-12">
<div class="input-group blmd-form">
<div class="blmd-line">
<input type="text" name="userid" autocomplete="off" id="username" class="form-control" required autofocus="" ng-model="user.name" ng-minlength="3" ng-maxlength="12" ng-model-options="{ allowInvalid: true }">
<label class="blmd-label">User Id</label>
</div>
<p class="login-error" ng-show="frominline.userid.$dirty && frominline.userid.$error.required">
<span style="color : red">required</span>
</p>
<p ng-show="frominline.userid.$error.minlength" class="help-block" style="color:red;">Username is too short.</p>
<p ng-show="frominline.userid.$error.maxlength" class="help-block" style="color:red;">Username is too long.</p>
</div>
<div class="input-group blmd-form">
<div class="blmd-line">
<input type="email" name="email" autocomplete="off" id="email" class="form-control" required autofocus="" ng-model="user.email">
<label class="blmd-label">Email</label>
</div>
<span class="login-error" ng-show="frominline.email.$error.required && frominline.email.$dirty" style="color:red;" ng-model-options="{ allowInvalid: true }">required</span>
<span class="login-error" ng-show="!frominline.email.$error.required && frominline.email.$error.email && frominline.email.$dirty" style="color:red;">invalid email</span>
</div>
<button type="reset" ng-click="resetform(frominline)">reset</button>
</form>
My js code:
app.controller('loginCtrl'['$scope',function('$scope'){
var user = this;
$scope.resetform(form){
user.name='';
user.email='';
$scope.frominline.$dirty = false;
$scope.frominline.$pristine = true;
$scope.frominline.$submitted = false;
}]);
Now, in first image, those are the validation errors.
Now, I hit the reset button and the validation errors are gone but in the second image I got required field.
Can you please help me removing or reseting the whole form on a button click?
I tried with many options like $setPristine() or $setValidity() but i can't fix this issue "required" error message.
Follows the image of the form with only required error message after clicking reset button:
The form is probably cleared, but those input fields are not. When you are display the error for a particular field (e.g. ng-show="frominline.userid.$error.minlength") include the state of the form as well (e.g. ng-show="frominline.$submitted && frominline.userid.$error.minlength").

Using ng-pattern to validate email in AngularJS

I'm new to Angular and have trouble getting the ng-pattern to validate the email address based on a REGEX. In fact the other default angular validation for email also changes behaviour and only shows an error if the entire field is empty when I insert ng-pattern. Initially tried using directives and controllers but found that the ng-pattern can achieve (in theory) the same effect of validating the email so decided to use this.
I have used several REGEX patterns and read about ng-pattern such as from: Regex validation of ng-patternForm validationEasy form validation and many other links but nothing works. Can anybody figure-out what I need to do to make things work ?
<form name="userForm" novalidate>
<div class="row">
<div class="large-12 medium-12 small-12 columns">
<label>Username</label>
<input type="email" name="username" placeholder="johnsmith#ashburton.com" ng-model="user.username" ng-maxlength="100" ng-model-options="{ updateOn: blur }" ng-pattern = "/^(?("")("".+?(?<!\)""#)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'*\+/=\?\^`\{\}\|~\w])*)(‌​?<=[0-9a-z])#))(?([)([(\d{1,3}\.){3}\d{1,3}])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-‌​z0-9][\-a-z0-9]{0,22}[a-z0-9]))$/" required />
<div class="error-container" ng-show="userForm.username.$dirty && userForm.username.$invalid">
<small class="error" ng-show="userForm.username.$error.required">
Your email is required.
</small>
<small class="error" ng-show="userForm.username.$error.email">
Please input a valid email.
</small>
<small class="error" ng-show="userForm.firstname.$error.maxlength">
Your email cannot be longer than 100 characters
</small>
</div>
</div>
</form>
Please change your ng-pattern to match this regex:
ng-pattern = '/^(([^<>()\[\]\.,;:\s#\"]+(\.[^<>()\[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()[\]\.,;:\s#\"]+\.)+[^<>()[\]\.,;:\s#\"]{2,})$/i'
This regex will give error if the section after # is left blank. This regex will accept unicode also.
Hope it helps.
There is an error with you regular expression. I used this simple email validator and it worked fine with few changes to display proper errors
<div class="row">
<div class="large-12 medium-12 small-12 columns">
<label>Username</label>
<input type="email" name="username" placeholder="johnsmith#ashburton.com" ng-model="user.username" ng-maxlength="100" ng-model-options="{ updateOn: blur }" ng-pattern="/^[a-z]+[a-z0-9._]+#[a-z]+\.[a-z.]{2,5}$/" required />
<div class="error-container" ng-show="userForm.username.$dirty && userForm.username.$error">
<small class="error" ng-show="userForm.username.$error.required">
Your email is required.
</small>
<small class="error" ng-show="userForm.username.$error.pattern">
Please input a valid email.
</small>
<small class="error" ng-show="userForm.username.$error.maxlength">
Your email cannot be longer than 100 characters
</small>
</div>
</div>
</div>
The problem was in my regex. I ended up using: ng-pattern='/^(([^<>()\[\]\\.,;:\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,}))$/' required />

AngularJS and Bootstrap: Red border on invalid input field on submit

I've this basic form implemented using AngularJS and Bootstrap:
http://jsfiddle.net/dennismadsen/0stwd03k/
HTML
<div ng-controller="MyCtrl">
<form class="well" name="formTest" ng-submit="save()">
<div class="form-group">
<label for="name">Name*</label>
<input type="name" class="form-control" id="name" placeholder="Enter name" required />
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
JavaScript
var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
$scope.save = function () {
};
}
Result
The Name input field is required. When I click the submit button, I need the input field to have a red border if it's invalid. How can this be done?
Alternatively, if I unfocus the input field and it's still not valid, it would be great that the red corder is shown on that time, instead of waiting for the form submit.
Twitter Bootstrap has an has-error class, so I would use this in conjunction with ng-class for the form group, then a label with the label and label-danger classes for good measure:
<div class="form-group" ng-class="{'has-error': errors.Name }">
<label for="name">Name*</label>
<input type="name" class="form-control" id="name" placeholder="Enter name" required />
<span class="label label-danger" ng-if="errors.Name">{{errors.Name}}</span>
</div>
Then in your controller, have an errors object, and set the Name property of this to a string when the name is invalid.
The first thing you were missing was adding ng-model='name' to input field, then only will the form become invalid once you click submit, otherwise the form will always be valid since it considers that there is no field present.
Then I'd add the submitted class on the submit click button, then put the border css like .submitted would be the parent and .ng-invalid would be the child so we can put the style on .submitted .ng-invalid
HTML
<div ng-controller="MyCtrl">
<form class="well" name="formTest" ng-class="{'submitted': submitted}" ng-submit="save()" >
<div class="form-group">
<label for="name">Name*</label>
<input type="name" class="form-control" id="name" placeholder="Enter name" ng-model="name" required />
</div>{{submitted}}
<button type="submit" class="btn btn-default" ng-click="submitted= true;">Submit</button>
</form>
</div>
CSS
.submitted .ng-invalid{
border: 1px solid red;
}
Working Fiddle
Hope this could help you, Thanks.
Basically you need angular to take over validation, so add novalidate to form. Also add ng-class to input field to determine wether to add error css
<form name="myForm" novalidate ng-submit="test()">
<input type="text" name="user" ng-model="user" required ng-class="myForm.user.$invalid && myForm.user.$dirty ? 'error' : ''">
<span style="color:red" ng-show="myForm.user.$dirty && myForm.user.$invalid">
<span ng-show="myForm.user.$error.required">Username is required. </span>
</span>
<p>
<input type="submit"
ng-disabled="myForm.user.$dirty && myForm.user.$invalid ||
myForm.email.$dirty && myForm.email.$invalid">
</p>
</form>
Good luck..

Is there a way to reset the $touched in Angular?

I'm trying to implement a "Reset" button for my form. Some of my text fields use the $touched to determine if an error is displayed. But once the $touched flag is set, when I reset the model, $touched is not reset and so my error messages remain visible.
<div class="col-sm-4" ng-class="{'has-error' : donationForm.firstName.$invalid && donationForm.firstName.$touched}">
<label for="firstName" class="control-label">First Name</label>
<input type="text" id="firstName" name="firstName" class="form-control"
ng-model="editableDonation.person.firstName" ng-required="true" ng-maxlength="20" />
<span class="help-block" ng-show="donationForm.firstName.$error.required && donationForm.firstName.$touched">
First Name is required.
</span>
<span class="help-block" ng-show="donationForm.firstName.$error.maxlength">
First Name is too long (20 max).
</span>
</div>
Is there a way to do that?
My resetForm:
$scope.resetForm = function () {
$scope.donationForm.$setPristine();
$scope.model = '';
$scope.donation = donationService.defaultDonation;
$scope.editableDonation = angular.copy($scope.donation);
};
http://plnkr.co/edit/Oa91ZkTatsddSA4oujQK
DeborahK89 helped me by pointing out that I could use:
$scope.donationForm.$setUntouched();

angular validation not working

I am using angular validation on an html page, where I have defined a form along with validation on the form. However, when I run the page, all the validations I have used on the page is visible. Is there a way I can hide all the validations?
<form ng-controller="validateCtrl"
name="loginForm" novalidate>
<p>UserName:<br>
<input type="text" name="uName" ng-model="uName" required>
<span style="color:red" ng-show="loginForm.uName.$dirty && loginForm.uName.$invalid && loginForm.uName.$error.required">
Username is required
</span>
</p>
<p>Password:<br>
<input type="text" name="pwd" ng-model="pwd" required>
<span style="color:red" ng-show="loginForm.pwd.$dirty && loginForm.pwd.$invalid">
<span ng-show="loginForm.pwd.$error.required">Password is required.</span>
</span>
</p>
<p>
<input type="submit" ng-click="popupuser()"
ng-disabled="loginForm.$invalid ">
</p>
</form>
<script src="https://code.angularjs.org/1.2.3/angular.min.js"></script>
Your code for form is fine please see here http://jsbin.com/figuve/1/edit
Make sure that your validateCtrl exist otherwise validation will not work plase see here
http://jsbin.com/figuve/2/edit
or
remove ng-controller="validateCtrl" from your form if you don't need it.
please see here http://jsbin.com/figuve/3/edit
You can try use variable to check is form submited, like that
<span ng-show="(loginForm.uName.$dirty || isSubmitted) && loginForm.uName.$error.required">Username is required</span>

Resources