Using ng-pattern to validate email in AngularJS - 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 />

Related

angularjs - ngMessages and validation not working as expected

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.

No form validation in my angular app

I tried and searched a lot, but no solution. The form validation in my angular app still not working.
I tried for example:
<form data-ng-controller="ValidationController" name="validationForm" novalidate="novalidate">
<div class="form-group">
<label for="username">Mail</label>
<input name="username"
type="email"
data-ng-model="formData.username"
required="required">
<span ng-show="form.username.$invalid">Invalid mail address</span>
</div>
<button type="submit" class="btn btn-primary" data-ng-disabled="formData.$invalid">Submit</button>
<pre>
<tt>formData = {{formData}}</tt><br/>
<tt>formData.$valid = {{formData.$valid}}</tt><br/>
<tt>formData.username.$valid = {{formData.username.$valid}}</tt><br/>
<tt>formData.username.$error = {{formData.username.$error}}</tt><br/>
<hr>
</pre>
</form>
Another one I tried:
<div class="row">
<div class="large-12 columns">
<label>Your email</label> <input type="email" placeholder="Email"
name="email" ng-model="signup.email" ng-minlength=3 ng-maxlength=20
required />
<div class="error-container"
ng-show="signup_form.email.$dirty && signup_form.email.$invalid">
<small class="error" ng-show="signup_form.email.$error.required">
Your email is required. </small> <small class="error"
ng-show="signup_form.email.$error.minlength"> Your email is required
to be at least 3 characters </small> <small class="error"
ng-show="signup_form.email.$error.email"> That is not a valid email.
Please input a valid email. </small> <small class="error"
ng-show="signup_form.email.$error.maxlength"> Your email cannot be
longer than 20 characters </small>
</div>
</div>
</div>
But the validation does not work. If I have to enable the validation? But for this I also didn't find anything. It seems, that validation is still enabled in Angular. But why it does not work in my app? All other things works fine.
Regards
Bytecounter
Try this:
<form data-ng-controller="ValidationController" name="validationForm" novalidate="novalidate">
<div class="form-group">
<label for="username">Mail</label>
<input name="username"
type="email"
data-ng-model="username"
required>
<span ng-show="validationForm.username.$invalid && validationForm.username.$dirty">Invalid mail address</span>
</div>
<button type="submit" class="btn btn-primary" data-ng-disabled="formData.$invalid">Submit</button>
<pre>
<tt>formData = {{validationForm}}</tt><br/>
<tt>formData.$valid = {{validationForm.$valid}}</tt><br/>
<tt>formData.username.$valid = {{validationForm.username.$valid}}</tt><br/>
<tt>formData.username.$error = {{validationForm.username.$error}}</tt><br/>
<hr>
</pre>
</form>
Actually your form is available by its name.
Check this plnkr.
You have some errors there.
First:
ng-show="form.username.$invalid"
You are referencing a variable form that does not exist in your scope. You should reference validationForm:
ng-show="validationForm.username.$invalid"
Second:
data-ng-disabled="formData.$invalid"
You are referencing the model of the input, instead of it's form object, that is, again, validationForm:
data-ng-disabled="validationForm.$invalid"
That should do.

Display errors in Angular when form invalid

Is there an automated way in Angular to display the error messages for invalid form. For Example, I have the below. It indeed works well in that it doesn't allow the user to submit but it doesn't give the user any automatic feedback to tell them that elements are required. Isn't there an automatic way to get it to print a field is required message by the field if the form is invalid on submit?
<div class="form-center">
<form name="loginform" class="forms" ng-controller="controllers.LoginController">
<fieldset> <legend><h3>Account Login</h3></legend>
<div class="advanced-search-item">
<label>Username:</label><br /> <input type="text" ng-model="username" name="username" placeholder="username" required><span class="error" ng-show="submitted && loginform.username.$error.required">Required!</span>
</div>
<div class="advanced-search-item">
<label>Password:</label><br />
<input type="password" name="password" ng-model="password" placeholder="password" required><span class="error" ng-show="submitted && loginform.username.$error.required">Required!</span>
</div>
<div class="advanced-search-item">
Login
</div>
</fieldset>
</form>
</div>
You will have to add some spans to show errors beside input fields like below
<span class="error" ng-show="submitted && loginform.username.$error.required">Required!</span>
<span class="error" ng-show="submitted && loginform.password.$error.required">Required!</span>
Hopefully you can keep this text in red color, below is the CSS
.error {
padding-left:10px;
color: #F00;
}
when form is submitted and if there are errors it will show above spans
Hope this helps

CSS with AngularJs custom validation

I'm having trouble getting a message to display when the field input is invalid. I can see the classes being correctly applied to the element i.e. ng-dirty ng-invalid ng-invalid-pattern so I just need to make the error message display. Is there an issue with my html?
Thanks!
<form ng-controller="FormCtrl" name="TestForm" action="http://myserver/api" method="post" novalidate>
<div class="form-group">
<input class="form-control" type="text" id="vld" name="vld" data-ng-pattern="/(^$)|(\b\d{9}\b)/" data-ng-model="model.tfn">
<span class="error" data-ng-show="model.tfn.$invalid">Correct input etc...</span>
</div>
</form>
The information you are looking for is part of the FormController. You need to setup a formController via ng-form directive:
<div class="form-group" ng-form="myForm">
<input class="form-control" type="text" id="vld" name="vld" data-ng-pattern="/(^$)|(\b\d{9}\b)/" data-mg-model="model.tfn">
<span class="error" data-ng-show="myForm.vld.$invalid">Correct input etc...</span>
</div>
If this is done you may access the information by [Name of the OFrmController].[Name of the input field].$invalid e.g. myForm.vld.$invalid

angular js validation not working using its own directives

i am using angular js directives but it's not working can any on know what i am doing wrong i follow angular js documentation but not working is there any library required is something wrong in my form .
loginView.html
<form class="form-horizontal" name="user_form" novalidate ng-submit='login()'>
<div class="modal-header">
<h3>Login</h3>
</div>
<div class="modal-body">
<div class="form-group">
<label for="login-Name" class="col-lg-3 form-label">User Name:</label>
<div class="col-lg-8">
<input type="email" class="form-control" id="login-Name" ng-model="user.username" name="login-Name" placeholder="User Name" required/>
<div class="error" ng-show="user_form.login-Name.$dirty && user_form.login-Name.$invalid">
<small class="error" ng-show="user_form.login-Name.$error.required">
User name is required.
</small>
</div>
</div>
</div>
<div class="form-group">
<label for="login-Password" class="col-lg-3 form-label">Password:</label>
<div class="col-lg-8">
<input type="password" class="form-control" id="login-Password" ng-model="user.password" name="login-Password" placeholder="Password" ng-minlength=6 ng-maxlength=20 required/>
<div class="error" ng-show="user_form.login-Password.$dirty && user_form.login-Password.$invalid">
<small class="error" ng-show="user_form.login-Password.$error.required">
Your Password is required.
</small>
<small class="error" ng-show="user_form.login-Password.$error.minlength">
Your Password is required to be at least 6 characters
</small>
<small class="error" ng-show="user_form.login-Password.$error.maxlength">
Your Password cannot be longer than 20 characters
</small>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">
<i class="icon-user icon-white"></i> Login
</button>
</div>
</form>
There are 2 mistakes in your code.
First one, you used - in your fields id (login-Name and login-Password). Replace them by _ (login_Name and login_Password). Angularjs see them as the substract operator and doesn't return an object to evaluate in the ng-show directives.
For the username (the email address), your error will never be displayed since the $error.required is set to false as soon as the field is not empty and $dirty is set to false if the field is empty. Your 2 conditions cannot be true at the same time.
For the password, you have the same problem for the required field, but your 2 other validations will work if you change your id.
Working example : Plunker

Resources