Add a custom validation using Angular Auto Validate - angularjs

First, I'm using Angular Auto Validate and it's working as expected, but I want to add a custom validation to compare passwords.
Here's my code actually:
<form role="form" name="changePasswordForm" novalidate="novalidate" ng-submit="changePassword()">
<div class="box-body">
<div class="form-group">
<label for="oldPassword">Old Password</label>
<input type="password" class="form-control" id="txtOldPassword" name="oldPassword" ng-model="data.oldPassword" placeholder="Old password" required="required" ng-pattern="/^[A-Za-z]+$/" ng-minlength="6" ng-maxlength="10" ng-pattern-err-type="badOldPassword">
</div>
<div class="form-group">
<label for="newPassword">New Password</label>
<input type="password" class="form-control" id="txtNewPassword" name="newPassword" ng-model="data.newPassword" placeholder="New password" required="required" ng-pattern="/^[A-Za-z]+$/" ng-minlength="6" ng-maxlength="10" ng-pattern-err-type="badNewPassword">
</div>
<div class="form-group">
<label for="confirmNewPassword">Confirm New Password</label>
<input type="password" class="form-control" id="txtConfirmNewPassword" name="confirmNewPassword" ng-model="data.confirmNewPassword" placeholder="Confirm new password" required="required" ng-pattern="/^[A-Za-z]+$/" ng-minlength="6" ng-maxlength="10" ng-pattern-err-type="badConfirmNewPassword">
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
var userApp = angular
.module("userModule", ['jcs-autoValidate'])
.run(function(defaultErrorMessageResolver) {
defaultErrorMessageResolver.getErrorMessages().then(function(errorMessages) {
errorMessages['badOldPassword'] = 'Old password must contain only alphabets.';
errorMessages['badNewPassword'] = 'New password must contain only alphabets..';
errorMessages['badConfirmNewPassword'] = 'Confirm password must contain only alphabets.';
})
})
.controller('userController', function($scope, $http, $log) {
$scope.data = {};
$scope.changePassword = function() {
alert('form submitted');
}
});

You should create a directive for this, as below:
angular.module('app', ['jcs-autoValidate'])
.controller('mainCtrl', function($scope) {
})
.directive('confirmPassword', function(defaultErrorMessageResolver) {
defaultErrorMessageResolver.getErrorMessages().then(function(errorMessages) {
errorMessages['confirmPassword'] = 'Please ensure the passwords match.';
});
return {
restrict: 'A',
require: 'ngModel',
scope: {
confirmPassword: '=confirmPassword'
},
link: function(scope, element, attributes, ngModel) {
ngModel.$validators.confirmPassword = function(modelValue) {
return modelValue === scope.confirmPassword;
};
scope.$watch('confirmPassword', function() {
ngModel.$validate();
});
}
};
});
<!DOCTYPE html >
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
<script src="https://cdn.rawgit.com/jonsamwell/angular-auto-validate/master/dist/jcs-auto-validate.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css" />
</head>
<body ng-controller="mainCtrl">
<div class="container main-content">
<form novalidate="novalidate">
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" placeholder="Password" ng-model="formModel.password" required="" ng-minlength="6" ng-maxlength="12" />
</div>
<div class="form-group">
<label for="exampleInputPassword">Confirm Password</label>
<input type="password" class="form-control" id="passwordConfirm" placeholder="Confirm Password" ng-model="formModel.confirmPassword" required="" ng-minlength="6" ng-maxlength="12" confirm-password="formModel.password" />
</div>
<div class="form-group">
<button class="btn btn-primary" type="submit">Register
</button>
</div>
</form>
</div>
</body>
</html>

Related

AngularJS and ASP.NET MVC data insert issue

I am inserting Data using AngularJS and ASP.NET MVC.
But I am facing issue that the data is inserted null.
What should I do?
This is AngularJS file:
var app = angular.module("myApp", []);
app.controller("myCtrl", function ($scope, $http) {
debugger;
$scope.InsertData = function () {
var Action = document.getElementById("btnSave").getAttribute("value");
if (Action == "Submit") {
$scope.User = {};
$scope.User.Username = $scope.Username;
alert($scope.Username);
$scope.User.Password = $scope.Password;
$scope.User.Email = $scope.Email;
$scope.User.Phone = $scope.Phone;
$scope.User.DOB = $scope.DOB;
$http({
method: "post",
url: "http://localhost:2776/Account/Insert_Employee",
datatype: "json",
data: JSON.stringify($scope.User)
}).then(function (response) {
alert("inserted");
});
}
};
});
This is HTML file:
<div class="tab-content" ng-controller="myCtrl">
<div class="tab-pane active" id="register">
<h3>Register Now !!!</h3>
<p class="text-muted">Be cool and join today. Meet millions</p>
<!--Register Form-->
<form name="registration_form" id='registration_form' class="form-inline">
<div class="row">
<div class="form-group col-xs-6">
<label for="Username" class="sr-only">User Name</label>
<input id="Username" ng-model="Username" class="form-control input-group-lg" type="text" name="Username" title="Enter User name" placeholder="User name" />
</div>
</div>
<div class="row">
<div class="form-group col-xs-12">
<label for="email" class="sr-only">Email</label>
<input ng-model="Email" id="email" class="form-control input-group-lg" type="text" name="Email" title="Enter Email" placeholder="Your Email" />
</div>
</div>
<div class="row">
<div class="form-group col-xs-12">
<label for="Phone" class="sr-only">Phone</label>
<input ng-model="Phone" id="Phone" class="form-control input-group-lg" type="text" name="Phone" title="Enter Phone" placeholder="Your Phone" />
</div>
</div>
<div class="row">
<div class="form-group col-xs-12">
<label for="password" class="sr-only">Password</label>
<input ng-model="Password" id="password" class="form-control input-group-lg" type="password" name="password" title="Enter password" placeholder="Password" />
</div>
</div>
<div class="row">
<p class="birth"><strong>Date of Birth</strong></p>
<div class="form-group col-sm-3 col-xs-6">
<label for="month" class="sr-only"></label>
<select class="form-control" id="day">
<option value="Day" disabled selected>Day</option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
<option>8</option>
<option>9</option>
<option>10</option>
<option>11</option>
<option>12</option>
<option>13</option>
<option>14</option>
<option>15</option>
<option>16</option>
<option>17</option>
<option>18</option>
<option>19</option>
<option>20</option>
<option>21</option>
<option>22</option>
<option>23</option>
<option>24</option>
<option>25</option>
<option>26</option>
<option>27</option>
<option>28</option>
<option>29</option>
<option>30</option>
<option>31</option>
</select>
</div>
<div class="form-group col-sm-3 col-xs-6">
<label for="month" class="sr-only"></label>
<select class="form-control" id="month">
<option value="month" ng-model="DOB" disabled selected>Month</option>
<option>Jan</option>
<option>Feb</option>
<option>Mar</option>
<option>Apr</option>
<option>May</option>
<option>Jun</option>
<option>Jul</option>
<option>Aug</option>
<option>Sep</option>
<option>Oct</option>
<option>Nov</option>
<option>Dec</option>
</select>
</div>
<div class="form-group col-sm-6 col-xs-12">
<label for="year" class="sr-only"></label>
<select class="form-control" id="year">
<option value="year" disabled selected>Year</option>
<option>2000</option>
<option>2001</option>
<option>2002</option>
<option>2004</option>
<option>2005</option>
<option>2006</option>
<option>2007</option>
<option>2008</option>
<option>2009</option>
<option>2010</option>
<option>2011</option>
<option>2012</option>
</select>
</div>
</div>
<div class="form-group gender">
<label class="radio-inline">
<input type="radio" name="optradio" checked>Male
</label>
<label class="radio-inline">
<input type="radio" name="optradio">Female
</label>
</div>
</form><!--Register Now Form Ends-->
<p>Already have an account?</p>
<button id="btnSave" value="Submit" class="btn btn-primary" ng-click="InsertData()">Register Now</button>
</div>
</div>
This is ASP.NET controller:
public string Insert_Employee(User User)
{
if (User != null)
{
using (Database1Entities Obj = new Database1Entities())
{
Obj.Users.Add(User);
Obj.SaveChanges();
return "Employee Added Successfully";
}
}
else
{
return "Employee Not Inserted! Try Again";
}
}
I am entering data, but data is inserted as null into db. What should I do no?
I have added <body ng-app="myApp">
According to me there is no error
can anyone help?
Try to wrote in this way your ajax call:
$http({
method: "post",
url: "http://localhost:2776/Account/Insert_Employee",
datatype: "json",
data: {user:$scope.User}
}).then(function (response) {
alert("inserted");
});

Confirm password validation angularjs material design

I want to display an error using angularjs, under the "confirm password" input which should say "Passwords don't match".
<form name="settingsForm" ng-submit="vm.login(vm.credentials)" novalidate>
<md-input-container class="md-block" flex-gt-sm="">
<label translate="MY_PROFILE_NEW_PASSWORD"></label>
<input type="password" name="newPassword" id="password"
ng-model="vm.newPassword"
required=""
ng-minlength="8"
md-maxlength="40">
<div ng-messages="settingsForm.newPassword.$error"
role="alert"
multiple="">
<div ng-message="required"
class="my-message"
translate="LOGIN_PASSWORD_INVALID">
</div>
<div ng-message="minlength"
class="my-message"
translate="MIN_8_CHARS">
</div>
</div>
</md-input-container>
<md-input-container class="md-block" flex-gt-sm="">
<label translate="MY_PROFILE_CONFIRM_NEW_PASSWORD"></label>
<input type="password"
name="confirmPassword"
id="confirmPassword"
ng-model="vm.confirmPassword"
required=""
confirm-password="vm.newPassword"
ng-minlength="8"
md-maxlength="40">
<div ng-messages="settingsForm.$error.confirmPassword"
role="alert" multiple="" >
<div ng-message="required"
class="my-message"
translate="LOGIN_PASSWORD_INVALID">
</div>
<div ng-message="minlength"
class="my-message"
translate="MIN_8_CHARS">
</div>
</div>
<div ng-message="required"
class="my-message"
translate="LOGIN_PASSWORD_INVALID">
</div>
<div ng-message="confirm-password"
class="my-message">
Passwords don't match.
</div>
</md-input-container>
<md-button class="md-raised md-primary btn-auth"
type="submit"
ng-disabled="settingsForm.$invalid"
translate="SUBMIT"
ng-click="vm.changePassword(vm)">
</md-button>
I need to make this form display error messages for each particular case.
I haven't found how "confirm-password" attribute should work for validation.
You have to create a Custom Directive. Try this.
<div data-ng-controller="PasswordController as vmPassword">
<form name="passwordForm">
<md-input-container class="md-block" flex-gt-sm>
<label>Password</label>
<input type="password"
name="password"
ng-model="vmPassword.password"
required
/>
<div ng-messages="passwordForm.password.$error" role="alert" class="form-errors first-name-error">
<div ng-message="required">Password is required.</div>
</div>
</md-input-container>
<md-input-container class="md-block" flex-gt-sm>
<label>Confirm Password</label>
<input type="password"
name="confirm_password"
ng-model="vmPassword.confirm_password"
required
compare-to="vmPassword.password"
/>
<div ng-messages="passwordForm.confirm_password.$error" role="alert" class="form-errors first-name-error">
<div ng-message="required">Password is required.</div>
<div ng-message="compareTo">Passwords do not match</div>
</div>
</md-input-container>
</form>
</div>
Custom Directive
(function () {
"use strict";
angular.module('app').directive('compareTo', compareTo);
compareTo.$inject = [];
function compareTo() {
return {
require: "ngModel",
scope: {
compareTolValue: "=compareTo"
},
link: function(scope, element, attributes, ngModel) {
ngModel.$validators.compareTo = function(modelValue) {
return modelValue == scope.compareTolValue;
};
scope.$watch("compareTolValue", function() {
ngModel.$validate();
});
}
};
}
})();
Goodluck .! :)
Demo here - http://embed.plnkr.co/UK4G4Lm5BCNNe5SWoA9r/

How to get an internal ng-model value?

I am working on SPA and I include HTML pages into one basic page by ng-include.Let's call this basic page as external and the included pages as internal.In an internal page I have set an input attribute to be ng-model="userd.Username" and in the external page i would like to get the value of this input.
In some internal page register.html there is the following code:
<div class="form-group">
<div class="form-group">
<span class="regForm text-danger">*</span> <input
ng-model="userd.Username" type="text" maxlength="10"
placeholder="Enter your name" class="form-control input-md"
required />
</div>
<div class="form-group">
<span class="regForm text-danger">*</span> <input
ng-model="userd.Password" type="password" maxlength="8"
placeholder="Enter your password" class="form-control input-md"
required />
</div>
<div class="form-group">
<span class="regForm text-danger">*</span><input
ng-model="userd.Nickname" type="text" maxlength="20"
placeholder="Enter your nickname" class="form-control input-md"
required />
</div>
<div class="form-group">
<input ng-model="userd.Description" type="text" maxlength="50"
placeholder="Enter description about you"
class="form-control input-md" />
</div>
<div class="form-group">
<input ng-model="userd.Photo" type="text"
placeholder="Enter photo URL" class="form-control input-md" />
</div>
<div class="form-group">
<button ng-click="registerBtn()" class="btn btn-primary">Register</button>
</div>
</div>
In the external page:
<div ng-include="'register.html'" ng-controller="registerCon" ng-show="logreg"></div>
I've tried to use the $rootscope as following in the main controller of the external page:
var appvar = angular.module('myApp', []);
//The Main Controller of the page (single web page)
appvar.controller('myCtrl',['$scope','$http','$rootScope',function($scope, $http,$rootScope) {
$rootScope.storedsession="";
}]);
And in the controller 'registerCon' I wrote:
appvar.controller('registerCon',['$scope','$http','$rootScope',function($scope, $http, $rootScope) {
$scope.registerBtn = function() {
console.log(this.userd);
$http.post("http://localhost:8080/ExampleServletv3/registeruser",this.userd)
.success(function(response) {
console.log(response);
setTimeout(function () {
$scope.$apply(function(){
$rootScope.storedsession=this.userd.Username;
console.log($rootScope.storedsession);
});
});
});
};
}]);
but it prints undefined for console.log($rootScope.storedsession); in the console,I also tried $scope instead of $rootScope but it didn't work too.
Can someone help me please?
Thanks

How to check for confirm password in the signup page using angularjs

I'm trying to write code for checking confirm password using angularjs.Can anyone please help me out regarding this issue ...
My signUp.html:
<html ng-app="Sample">
<head>
<link rel="stylesheet" href="../css/bootstrap.min.css" />
<link rel="stylesheet" href="../css/custom.css" />
<script src="../js/jquery.min.js"></script>
<script src="../js/bootstrap.min.js"></script>
<script src="../js/angular.min.js"></script>
<script src="../js/angular-animate.min.js"></script>
<script src="../js/angular-route.min.js"></script>
<script src="../js/script.js"></script>
<script src="https://code.angularjs.org/1.3.0-rc.2/angular-messages.js"></script>
</head>
<body>
<div class="container" id="wrapper1" align="center" ng-controller="RegistrationController as registration" >
<div>
<img id="logoDiv" src="../images/favicon.png">
</div>
<div id="loginDiv">
<h2>Sign up</h2>
<form>
<input type="text" class="resizedTextbox" ng-model="email" placeholder="Email" /><br> <br>
<input type="text" class="resizedTextbox" placeholder="Password" /><br><br>
<input type="text" class="resizedTextbox" placeholder="Verify Password" /><br><br>
<a href="#/signUp"> <button class="resizedBtn" value="SIGN UP">SignUp
</button></a>
</form>
</div>
</div>
</body>
</html>
I've had the same question as you, and found a great answer here. I used the 'nxEqual' directive and my form inputs look like this:
<input type="password" name="password" ng-model="user.password" placeholder="Password"
ng-required="true"
ng-minlength="8">
<input type="password" name="passwordConfirm" ng-model="user.passwordConfirm" placeholder="Confirm Password"
ng-required="true"
ng-minlength="8"
nx-equal="user.password">
To display a message like "Passwords do not match", i used this line ("signUpForm" is the name of myform.):
<div ng-show="signUpForm.passwordConfirm.$error.nxEqual"> Passwords do not match.</div >
You can assign a ng-model to both password fields , and below the text fields use an ng-show with condition that if both password match then show success message
<form>
<input type="text" class="resizedTextbox" ng-model="email" placeholder="Email" /><br> <br>
<input type="text" class="resizedTextbox" ng-model="password" placeholder="Password" /><br><br>
<input type="text" class="resizedTextbox" ng-model="verify-password" placeholder="Verify Password" /><br><br>
<div ng-show="password === verify-password" > password matched </div>
<a href="#/signUp"> <button class="resizedBtn" value="SIGN UP">SignUp
</button></a>
</form>
similarly you can use ng-hide to show error message
Use like this by using custom directive "verifyPassword" & use form_name.password2.$error.noMatch property in ng-show, to display the error:
<input type="password" name="password" class="form-control" placeholder="Enter password"/> // password html
<input verifyPassword type="text" name="password2" class="resizedTextbox" placeholder="Verify Password"/> //confirm password html
And use this directive,
Buyer.directive('verifyPassword', function () {
return {
require: 'ngModel',
link: function (scope, elm, attrs, ctrl) {
ctrl.$parsers.unshift(function (viewValue, $scope) {
var noMatch = viewValue != scope.regForm.password.$viewValue
ctrl.$setValidity('noMatch', !noMatch)
return (noMatch)?noMatch:viewValue;
})
}
}
});

AngularJS password confirmation noMatch not working?

I have this script here:
angular.module('UserValidation', []).directive('validPasswordC', function () {
return {
require: 'ngModel',
link: function (scope, elm, attrs, ctrl) {
ctrl.$parsers.unshift(function (viewValue, $scope) {
var noMatch = viewValue != scope.signupForm.password.$viewValue
ctrl.$setValidity('noMatch', !noMatch)
})
}
}
});
And here's the html:
<div class="fieldset" ng-class="{'has-error':formData.password.$invalid && !formData.password.$pristine}">
<label>Password</label>
<input type="password" id="password" name="password" ng-model="formData.password" ng-minlength="8" ng-maxlength="20" ng-pattern="/(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z])/" placeholder="password" required />
<p ng-show="signupForm.password.$error.required" class="error">*</p>
<p ng-show="signupForm.password.$error.minlength" class="error">
Passwords must be between 8 and 20 characters.</p>
<p ng-show="signupForm.password.$error.pattern" class="error">
Must contain one lower & uppercase letter, and one non-alpha character (a number or a symbol.)</p>
</div>
<div class="fieldset" ng-class="{'has-error':formData.password_c.$invalid && !formData.password_c.$pristine}">
<label for="password_c">Confirm Password</label>
<input type="password" id="password_c" name="password_c" ng-model="formData.password_c" placeholder="confirm password" valid-password-c required />
<p ng-show="signupForm.password_c.$error.noMatch" class="error">Passwords do not match.</span>
<p ng-show="signupForm.password_c.$error.required" class="error">*</p>
</div>
The character validation for password is working, but the "noMatch" function for confirm password is not working.
What might be the problem? Thanks! :)
You need to pass your original password to directive as well/
Please see working demo below
var app = angular.module('app', []);
app.directive('validPasswordC', function() {
return {
require: 'ngModel',
scope: {
reference: '=validPasswordC'
},
link: function(scope, elm, attrs, ctrl) {
ctrl.$parsers.unshift(function(viewValue, $scope) {
var noMatch = viewValue != scope.reference
ctrl.$setValidity('noMatch', !noMatch);
return (noMatch)?noMatch:!noMatch;
});
scope.$watch("reference", function(value) {;
ctrl.$setValidity('noMatch', value === ctrl.$viewValue);
});
}
}
});
app.controller('homeCtrl', function($scope) {
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="homeCtrl">
<p>Password:{{formData.password}}</p>
<form name="signupForm">
<div class="fieldset" ng-class="{'has-error':formData.password.$invalid && !formData.password.$pristine}">
<label>Password</label>
<input type="password" id="password" name="password" ng-model="formData.password" ng-minlength="8" ng-maxlength="20" ng-pattern="/(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z])/" placeholder="password" required />
<p ng-show="signupForm.password.$error.required" class="error">*</p>
<p ng-show="signupForm.password.$error.minlength" class="error">
Passwords must be between 8 and 20 characters.</p>
<p ng-show="signupForm.password.$error.pattern" class="error">
Must contain one lower & uppercase letter, and one non-alpha character (a number or a symbol.)</p>
</div>
<div class="fieldset" ng-class="{'has-error':formData.password_c.$invalid && !formData.password_c.$pristine}">
<label for="password_c">Confirm Password</label>
<input type="password" id="password_c" name="password_c" ng-model="formData.password_c" placeholder="confirm password" valid-password-c="formData.password" required />
<p ng-show="signupForm.password_c.$error.noMatch" class="error">Passwords do not match.</span>
<p ng-show="signupForm.password_c.$error.required" class="error">*</p>
</div>
</form>
</div>
</div>
The easiest is this one.But i don't know this is the good way of coding.
<input ng-model="password" name="user_password" type="password" ng-required="true" >
<input ng-model="confirmPassword" name="user_password" type="password" ng-required="true" >
<span ng-show="pasword !== confirmPassword">Password mismatch</span>
The following also will work to verify the confirm password.
<div ng-app="myapp" ng-controller="mainController as mnCtrl">
<form name="mnCtrl.useradd" ng-submit="mnCtrl.frmAdd()" novalidate role="form">
<input ng-model="mnCtrl.fields.password" name="user_password" type="password" ng-required="true" >
<input ng-model="mnCtrl.fields.cpassword" name="user_cpassword" type="password" ng-required="true" >
<div ng-show=" mnCtrl.useradd.user_cpassword.$viewValue != '' && (mnCtrl.useradd.user_password.$viewValue != mnCtrl.useradd.user_cpassword.$viewValue) ">Fields do not match!</div>
</form>
</div>

Resources