angular form validation for pass confirmation - javascript

I'm trying to do a validation in angular using ngMessage and min/maxlength, so the scenario is if min != min then the submit button should be disabled. and if not matched button should be disabled too; only allow to submit the form if all is matched and equal.
Also the ng-show isn't working properly because of the min/maxlenght it won't disappear even the password is matched.
http://jsfiddle.net/tkgfa1qh/
<input required
data-ng-model-options="{debounce: 1000}"
data-ng-model="vm.registerForm.Password"
class="form-control search-input inverted text-box single-line text-box single-line"
data-val="true" data-val-required="The password field is required."
id="register-password"
name="password"
placeholder="Password"
type="password"
value=""
data-ng-minlength="6"
data-ng-maxlength="12"/>
<span data-ng-show="vm.registerForm.Password !== vm.registerForm.ConfirmPassword" style="color: red;">Password is not matched</span>
<div class="mt-10" data-ng-messages="registerForm.password.$error">
<!--<p data-ng-message="vm.registerForm.Password !== vm.registerForm.ConfirmPassword">Password is not matched</p>-->
<p data-ng-message="minlength">Password is too short (min of 6 characters)</p>
<p data-ng-message="maxlength">Password is too long (max of 12 characters)</p>
</div>
</div>
<div class="col-sm-6 ">
<label for="register-confirm-password" class="hidden">Confirm Password </label>
<input
required
data-ng-model="vm.registerForm.ConfirmPassword"
class="form-control search-input inverted text-box single-line text-box single-line"
data-val="true"
data-val-required="The password field is required."
id="register-confirm-password"
name="ConfirmPassword"
placeholder="Confirm Password"
type="password"
value=""/>
</div>
</div>
<div class="form-group clearfix">
<div class="col-sm-12">
<label for="submitForm" class="hidden">Submit</label>
<input
data-ng-disabled="vm.registerForm.Password !== vm.registerForm.ConfirmPassword ? vm.registerForm.Password : disabled || registerForm.$invalid
|| registerForm.Password.$error.minlength < registerForm.Password.$error.minlength"
type="button"
id="submitForm"
data-ng-click="vm.postRegisterForm()"
value="Register"
class="btn-main maxw-200"
data-ng-class="{'orange': registerForm.$valid}">
</div>
</div>

See this updated JSFIddle where i added ng-app. And included ngMessages.
JavaScript
var app = angular.module("MyApp", ["ngMessages"]);
HTML
<form ng-app="MyApp" action="" name="registerForm">

Related

maxlegth not working using template driven form in angular 6

I am developing one register form in that form i need maxlength validation but using template driven form can't show maxlength alert message.
<input type="text" class="form-control" placeholder="Enter Name"maxlength="4"
name="name" [(ngModel)]="name" ngModel required #username="ngModel">
<div *ngIf="username.invalid && (username.dirty || username.touched)">
<p style="color:red;font-size:10px;" *ngIf='username.invalid.maxlength'>
You enter only 4 characters.
</p>
</div>
Try:
<form name="form" role="form" #form="ngForm">
<div class="form-group">
<label class="form-control-label" for="userName">UserName</label>
<input
type="userName"
class="form-control"
id="userName"
name="userName"
#userNameInput="ngModel" //ngModel variable and template variable should not be the same
[(ngModel)]="userName"
minlength=4
maxlength=50
required>
<div *ngIf="userNameInput.dirty && userNameInput.invalid">
<small class="form-text text-danger" *ngIf="userNameInput.errors.required">
Your userName is required.
</small>
<small class="form-text text-danger" *ngIf="userNameInput.errors.minlength">
Your userName is required to be at least 4 characters.
</small>
<small class="form-text text-danger" *ngIf="userNameInput.errors.maxlength">
Your username cannot be longer than 50 characters.
</small>
</div>
</div>
</form>
DEMO
For me, the issue was input type="number".
Once I removed the type number maxLength worked.
Angular version: 8
username.invalid will be username.errors?
*ngIf="username.errors?.maxlength"
so there are a couple of steps to follow to validate your input like
please check this
<input
type="text"
placeholder="Your full name"
name="name"
ngModel
#userName="ngModel"
maxlength="4"
required>
<div *ngIf="userName.errors?.minlength && userName.touched" class="error">
Minimum of 4 characters
</div>
?.prop is called the “Safe navigation operator”
that means it avoids an exception for null and undefined values in in property paths
As if you use maxlength property for input type it does not allows a user to type anything beyond that length [As I tested in Chrome].
So if you want to display an alert or error message then you can check for input's length property and display error message:
HTML:
Remove maxlength from input type and check for username.value?.length in if condition
<input type="text" class="form-control" placeholder="Enter Name" name="username" [(ngModel)]="name" ngModel required #username="ngModel">
<div *ngIf="username.value?.length > 4">
<p style="color:red;font-size:10px;">
You enter only 4 characters.
</p>
</div>
WORKING DEMO
I needed to validate the length using the template only and I need it to invalidate the form as well so here is what I did using pattern
<textarea class="form-control" id="Command" rows="3" name="dialogCommand" pattern="^(.|\n){0,4000}$" #comment="ngModel" [(ngModel)]="comment" [ngClass]="{ 'is-invalid': comment?.errors?.pattern }"></textarea>
<div class="text-danger small" *ngIf="comment?.errors?.pattern">The comment cannot be greater than 4000 characters long</div>
This will count on multiple lines.
Hope this helps someone

Angular template driven form on submit validation

In angular js, we have $submitted to populate error messages on submit click.
How can we display all validation errors on submit click in Angular
HTML:
<form #nameForm="ngForm" novalidate (ngSubmit)="saveNameForm(formModel)">
<div class="form-group">
<label for="inputName" class="form-control-label"> Name</label>
<input type="text" id="inputName" name="lotCode [(ngModel)]="formModel.name" #lotCode="ngModel" aria-describedby="nameHelp"
autocomplete="new-password" required>
<small id="nameHelp" class="text-danger" *ngIf="lotCode.invalid && lotCode.touched">Required</small>
</div>
<div class="form-group">
<label for="inputDescription" class="form-control-label"> Description</label>
<input type="text" id="inputDescription" name="desCode" [(ngModel)]="formModel.description" #desCode="ngModel" aria-describedby="descriptionHelp"
autocomplete="new-password" required>
<small id="descriptionHelp" class="text-danger" *ngIf="desCode.invalid && desCode.touched">Required</small>
</div>
<button type="submit">Submit </button>
</form>
Component:
export class AppComponent {
formModel: FormModel= new FormModel();
saveNameForm(formModel){
console.log(formModel)
}
}
export class FormModel {
name: string;
description:string;
}
https://stackblitz.com/edit/angular-rizsuy?file=src%2Fapp%2Fapp.component.ts
Here is the solution:
https://stackblitz.com/edit/angular-8jaaqz?file=src%2Fapp%2Fapp.component.html
You should use a variable to set submitted
if submitted then will display error
Angular uses the same form validation that native HTML5 does. Just do this in an Angular context. In the following example, we can use *ngIf to control the display of the messages, and .dirty and .touched to determine if the user interacted with the input.
Example from docs:
<input id="name" name="name" class="form-control"
required minlength="4" appForbiddenName="bob"
[(ngModel)]="hero.name" #name="ngModel" >
<div *ngIf="name.invalid && (name.dirty || name.touched)"
class="alert alert-danger">
<div *ngIf="name.errors.required">
Name is required.
</div>
<div *ngIf="name.errors.minlength">
Name must be at least 4 characters long.
</div>
<div *ngIf="name.errors.forbiddenName">
Name cannot be Bob.
</div>
</div>

Angular ng-messages: how to check password confirmation?

THE SITUATION:
I am using ng-messages directive for instant validation in my angular app. Everything is working fine except one thing: i need to validate the field 'password confirmation' and don't know how to do.
THE CODE:
<form name="autentication_form" novalidate="" ng-submit="submit_register()">
<label class="item item-input">
<span class="input-label">Email</span>
<input type="text" name="email" ng-model="registerData.email" required>
<div class="form-errors" ng-messages="autentication_form.email.$error" role="alert" ng-if='autentication_form.email.$dirty'>
<div class="form-error" ng-message="required">You did not enter the email</div>
</div>
</label>
<label class="item item-input">
<span class="input-label">Password</span>
<input type="password" name="password" ng-model="registerData.password" required>
<div class="form-errors" ng-messages="autentication_form.password.$error" role="alert" ng-if='autentication_form.password.$dirty'>
<div class="form-error" ng-message="required">Please enter the password</div>
</div>
</label>
<label class="item item-input">
<span class="input-label">Password confirmation</span>
<input type="password" name="password_confirmation" ng-model="registerData.password_confirmation" required>
<div class="form-errors" ng-messages="autentication_form.password_confirmation.$error" role="alert" ng-if='autentication_form.password_confirmation.$dirty'>
<div class="form-error" ng-message="required">Password confirmation required</div>
</div>
</label>
</form>
THE QUESTION:
How can i check that the password confirmation match using ng-messages?
The easiest approach is to use a pattern. Works fine for me!
<input type="password" name="new_password1" ng-model="new_password1">
<input type="password" name="new_password2" ng-pattern="\b{{new_password1}}\b" ng-model="new_password2">
<div ng-messages="passwordForm.new_password2.$error">
<div ng-message="pattern">Not equal!!!</div>
</div>
The best approach is to use a directive. The major point of problem here is that both password and password confirmation inputs need to be watched.
Here's the solution that could help
angular.module('app', ['ngMessages'])
.controller('ctrl', function($scope) {
$scope.registerData = {};
})
.directive('confirmPwd', function($interpolate, $parse) {
return {
require: 'ngModel',
link: function(scope, elem, attr, ngModelCtrl) {
var pwdToMatch = $parse(attr.confirmPwd);
var pwdFn = $interpolate(attr.confirmPwd)(scope);
scope.$watch(pwdFn, function(newVal) {
ngModelCtrl.$setValidity('password', ngModelCtrl.$viewValue == newVal);
})
ngModelCtrl.$validators.password = function(modelValue, viewValue) {
var value = modelValue || viewValue;
return value == pwdToMatch(scope);
};
}
}
});
<html ng-app="app">
<head>
<script data-require="angular.js#~1.4.3" data-semver="1.4.3" src="https://code.angularjs.org/1.4.3/angular.js"></script>
<script data-require="angular-messages#1.4.3" data-semver="1.4.3" src="https://code.angularjs.org/1.4.3/angular-messages.js"></script>
<script src="https://code.angularjs.org/1.3.15/angular.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="ctrl">
<form name="autentication_form" novalidate="" ng-submit="submit_register()">
<label class="item item-input">
<span class="input-label">Email</span>
<input type="text" name="email" ng-model="registerData.email" required="" />
<div class="form-errors" ng-messages="autentication_form.email.$error" ng-if='autentication_form.email.$touched'>
<span class="form-error" ng-message="required">You did not enter the email</span>
</div>
</label>
<label class="item item-input">
<span class="input-label">Password</span>
<input type="password" name="password" ng-model="registerData.password" required />
<div class="form-errors" ng-messages="autentication_form.password.$error" ng-if='autentication_form.password.$touched'>
<span class="form-error" ng-message="required">Please enter the password</span>
</div>
</label>
<label class="item item-input">
<span class="input-label">Password confirmation</span>
<input type="password" name="password_confirmation" ng-model="registerData.password_confirmation" required="" confirm-pwd="registerData.password" />
<div class="form-errors" ng-messages="autentication_form.password_confirmation.$error" ng-if='autentication_form.password_confirmation.$touched'>
<span class="form-error" ng-message="required">Password confirmation required</span>
<span class="form-error" ng-message="password">Password different</span>
</div>
</label>
</form>
</body>
</html>
When developing, you can face the fact that you need to create your own checks, which will affect the validity of the form. If these checks are simple, such as a comparison of the two values, it is better to use a general guideline, than write your own checks for each situation. Look at use-form-error directive.
Live example on jsfiddle.
angular.module('ExampleApp', ['use', 'ngMessages'])
.controller('ExampleController', function($scope) {
});
.errors {
color: maroon
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular-messages.min.js"></script>
<script src="https://cdn.rawgit.com/Stepan-Kasyanenko/use-form-error/master/src/use-form-error.js"></script>
<div ng-app="ExampleApp">
<div ng-controller="ExampleController">
<form name="ExampleForm">
<label>Password</label>
<input ng-model="password" required />
<br>
<label>Confirm password</label>
<input ng-model="confirmPassword" name="confirmPassword" use-form-error="isNotSame" use-error-expression="password && confirmPassword && password!=confirmPassword" required />
<div ng-show="ExampleForm.$error.isNotSame" class="errors">Passwords Do Not Match!</div>
<div ng-messages="ExampleForm.confirmPassword.$error" class="errors">
<div ng-message="isNotSame">
Passwords Do Not Match (from ng-message)!
</div>
</div>
</form>
</div>
</div>
Here's what I did (using ng-pattern):
<md-input-container class="md-block">
<label>New Password</label>
<input ng-model="user.password" name="password" type="password" required ng-pattern="'.{8,}'" />
<div ng-messages="form.password.$error">
<div ng-message="required">Password required.</div>
<div ng-message="pattern">Password must be at least 8 characters.</div>
</div>
</md-input-container>
<md-input-container class="md-block">
<label>Confirm Password</label>
<input ng-model="user.confirmPassword" name="confirmPassword" type="password" ng-pattern="user.password|escapeRegex" required />
<div ng-messages="form.confirmPassword.$error">
<div ng-message="required">Password confirmation required.</div>
<div ng-message="pattern">Passwords do not match.</div>
</div>
</md-input-container>
And the following filter converts the ng-pattern regex to a literal:
module.filter('escapeRegex', function(){
return function(str){
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
});
ngMessage works by adding $error.message_field_name to the DOM field name in the form object (within the scope of course). So if your DOM form name is autentication_form and the DOM field name is password_confirmation, you need to set $scope.autentication_form.password_confirmation.$error.nomatch (or whatever ngMessage name you want) to true to display the "Doesn't match" error.
Markup:
<input type="password" name="password_confirmation" ng-model="registerData.password_confirmation" required />
<div ng-messages="autentication_form.password_confirmation.$error">
<div ng-message="required">Please repeat your password.</div>
<div ng-message="nomatch">Doesn't match.</div>
</div>
</div>
Code, nothing special, just watching both passwords:
$scope.$watch("registerData.password + registerData.password_confirmation", function () {
$scope.autentication_form.password_confirmation.$error.nomatch = $scope.registerData.password !== $scope.registerData.password_confirmation;
});
i did using only ionic(html) validations.
New Password
New Password is required
<label class="item item-input inputRadius">
<span class="input-label">Confirm Password</span>
<input type="password" placeholder="Confirm Password" ng-model="passwordUpdateInfo.confirmPassword" name="confirmPassword" required>
</label>
<div ng-show="passwordUpdateForm.$submitted || passwordUpdateForm.confirmPassword.$touched">
<div ng-show="passwordUpdateForm.confirmPassword.$error.required" class="errorMessage">Confirm Password is required</div>
</div>
<div ng-show="passwordUpdateInfo.confirmPassword.length > 0 && passwordUpdateInfo.confirmPassword != passwordUpdateInfo.newPassword">
Password not match..(amar from india)
</div>
<button class="button button-positive button-block" ng-disabled="passwordUpdateInfo.confirmPassword.length > 0 && passwordUpdateInfo.confirmPassword != passwordUpdateInfo.newPassword">Update</button>

Confirm password custom directive is not working in Angular

I try to implement confirm password validation in angular view. write new
directive in app.js
and add compare-to in confirm password text box
<div class="form-group">
<label class="control-label col-sm-2" for="pwd">Password:</label>
<div class="col-sm-10">
<input type="password"
class="form-control"
placeholder="Enter password"
ng-model="Password"
ng-minlength="5">
<span class="validationMessage" ng-show="frm.password.$dirty && frm.password.$error.required">Required!</span>
<span class="validationMessage" ng-show="frm.password.$dirty && frm.password.$error.minlength">Min length 5!</span>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="pwd">Confirm Password:</label>
<div class="col-sm-10">
<input type="password"
class="form-control"
ng-model="ConfirmPassword"
required
compare-to="Password"
placeholder="Enter Confirm password">
<span class="validationMessage" ng-show="frm.ConfirmPassword.$error">Required!</span>
</div>
</div>
But the confirm password is not shows any validation. and show a error message Cannot set property 'compareTo' of undefined in chrome.
It's working, mostly. You just have little logic flaws there.
First of all, using <label for="x"> expects template to have a element with id="x" present. Nothing major there but when you check for form validity you should refer to your form fields, not underlying model.
So instead of frm.<ng-model-var>.$error you should type in frm.<form-field-name>.$error.
You need to add names for your inputs, and check your form validation logic once more. This should work fine for your password.
<!-- added required, input name, changed validation logic -->
<input type="password"
name="password"
class="form-control"
placeholder="Enter password"
ng-model="Password"
required
ng-minlength="5" />
<span class="validationMessage"
ng-show="frm.password.$error.required">
Required!
</span>
<span class="validationMessage"
ng-show="frm.password.$dirty && frm.password.$error.minlength">
Min length 5!
</span>
and this for your confirm password.
<!-- added input name, changed validation logic -->
<input type="password"
name="confirmpassword"
class="form-control"
placeholder="Enter Confirm password"
ng-model="ConfirmPassword"
required
compare-to="Password" />
<span class="validationMessage"
ng-show="frm.password.$valid && frm.confirmpassword.$invalid">
Passwords do not match!
</span>
Try with updated versions
http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js
https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.2/angular-route.min.js
and in your controller.js add this..
'ngRoute'
var loginApp = angular.module('indexApp', ['authModule','requestModule','ngRoute']);

Validate phone number using angular js

Want to set phone-number to 10 digits, How can I do this using Angular js.
This is what I have tried:
<form class="form-horizontal" role="form" method="post" name="registration" novalidate>
<div class="form-group" ng-class="{'has-error': registration.phone.$error.number}">
<label for="inputPhone" class="col-sm-3 control-label">Phone :</label>
<div class="col-sm-9">
<input type="number"
class="form-control"
ng-minlength="10"
ng-maxlength="10"
id="inputPhone"
name="phone"
placeholder="Phone"
ng-model="user.phone"
ng-required="true">
<span class="help-block"
ng-show="registration.phone.$error.required &&
registration.phone.$error.number">
Valid phone number is required
</span>
<span class="help-block"
ng-show="((registration.password.$error.minlength ||
registration.password.$error.maxlength) &&
registration.phone.$dirty) ">
phone number should be 10 digits
</span>
</div>
</div>
</form>
But I am not getting the validation error.
Try this:
<form class="form-horizontal" role="form" method="post" name="registration" novalidate>
<div class="form-group" ng-class="{'has-error': registration.phone.$error.number}">
<label for="inputPhone" class="col-sm-3 control-label">Phone :</label>
<div class="col-sm-9">
<input type="number"
class="form-control"
ng-minlength="10"
ng-maxlength="10"
id="inputPhone"
name="phone"
placeholder="Phone"
ng-model="user.phone"
ng-required="true">
<span class="help-block"
ng-show="registration.phone.$error.required ||
registration.phone.$error.number">
Valid phone number is required
</span>
<span class="help-block"
ng-show="((registration.phone.$error.minlength ||
registration.phone.$error.maxlength) &&
registration.phone.$dirty) ">
phone number should be 10 digits
</span>
Check this answer
Basically you can create a regex to fulfil your needs and then assign that pattern to your input field.
Or for a more direct approach:
<input type="number" require ng-pattern="<your regex here>">
More info # angular docs here and here (built-in validators)
You can also use ng-pattern ,[7-9] = > mobile number must start with 7 or 8 or 9 ,[0-9] = mobile number accepts digits ,{9} mobile number should be 10 digits.
function form($scope){
$scope.onSubmit = function(){
alert("form submitted");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
<div ng-app ng-controller="form">
<form name="myForm" ng-submit="onSubmit()">
<input type="number" ng-model="mobile_number" name="mobile_number" ng-pattern="/^[7-9][0-9]{9}$/" required>
<span ng-show="myForm.mobile_number.$error.pattern">Please enter valid number!</span>
<input type="submit" value="submit"/>
</form>
</div>
You can also use ng-pattern and I feel that will be a best practice. Similarly try to use ng-message. Please look the ng-pattern attribute on the following html. The code snippet is partial but hope you understand it.
angular.module('myApp', ['ngMessages']);
angular.module("myApp.controllers",[]).controller("registerCtrl", function($scope, Client) {
$scope.ph_numbr = /^(\+?(\d{1}|\d{2}|\d{3})[- ]?)?\d{3}[- ]?\d{3}[- ]?\d{4}$/;
});
<form class="form-horizontal" role="form" method="post" name="registration" novalidate>
<div class="form-group" ng-class="{ 'has-error' : (registration.phone.$invalid || registration.phone.$pristine)}">
<label for="inputPhone" class="col-sm-3 control-label">Phone :</label>
<div class="col-sm-9">
<input type="number" class="form-control" ng-pattern="ph_numbr" id="inputPhone" name="phone" placeholder="Phone" ng-model="user.phone" ng-required="true">
<div class="help-block" ng-messages="registration.phone.$error">
<p ng-message="required">Phone number is required.</p>
<p ng-message="pattern">Phone number is invalid.</p>
</div>
</div>
</div>
</form>
use ng-intl-tel-input to validate mobile numbers for all countries. you can set default country also.
on npm: https://www.npmjs.com/package/ng-intl-tel-input
more details: https://techpituwa.wordpress.com/2017/03/29/angular-js-phone-number-validation-with-ng-intl-tel-input/
An even cleaner and more professional look I have found is to use AngularUI Mask. Very simple to implement and the mask can be customized for other inputs as well. Then a simple required validation is all you need.
https://angular-ui.github.io/
<form name = "numberForm">
<div>
<input type="number"
placeholder = "Enter your phonenumber"
class = "formcontroll"
name = "numbers"
ng-minlength = "10"
ng-maxlength = "10"
ng-model="phno" required/>
<p ng-show = "numberForm.numbers.$error.required ||
numberForm.numbers.$error.number">
Valid phone number is required</p>
<p ng-show = "((numberForm.numbers.$error.minlength ||
numberForm.numbers.$error.maxlength)
&& numberForm.numbers.$dirty)">
Phone number should be 10 digits</p><br><br>
</div>
</form>
Use ng-pattern, in this example you can validate a simple patern with 10 numbers, when the patern is not matched ,the message is show and the button is disabled.
<form name="phoneNumber">
<label for="numCell" class="text-strong">Phone number</label>
<input id="numCell" type="text" name="inputCelular" ng-model="phoneNumber"
class="form-control" required ng-pattern="/^[0-9]{10,10}$/"></input>
<div class="alert-warning" ng-show="phoneNumber.inputCelular.$error.pattern">
<p> write a phone number</p>
</div>
<button id="button" class="btn btn-success" click-once ng-disabled="!phoneNumber.$valid" ng-click="callDigitaliza()">Buscar</button>
Also you can use another complex patern like
^+?\d{1,3}?[- .]?(?(?:\d{2,3}))?[- .]?\d\d\d[- .]?\d\d\d\d$
, for more complex phone numbers
<div ng-class="{'has-error': userForm.mobileno.$error.pattern ,'has-success': userForm.mobileno.$valid}">
<input type="text" name="mobileno" ng-model="mobileno" ng-pattern="/^[7-9][0-9]{9}$/" required>
Here "userForm" is my form name.

Categories