Directives.directive("passwordVerify",function(){
return {
require:"ngModel",
link: function(scope,element,attrs,ctrl){
ctrl.$parsers.unshift(function(viewValue){
var origin = scope.$eval(attrs["passwordVerify"]);
if(origin!==viewValue){
ctrl.$setValidity("passwordVerify",false);
return undefined;
}else{
ctrl.$setValidity("passwordVerify",true);
return viewValue;
}
});
}
};
});
html:
<input data-ng-model='user.password' type="password" name='password' placeholder='password' required>
<input data-ng-model='user.password_verify' type="password" name='confirm_password' placeholder='confirm password' required data-password-verify="user.password">
암호 모두 같을 경우, 주어진 2 암호란이 필드용 양식에 영향을 받은 다음 필드 값은 디렉티브을 유효합니다. 문제는 작동하잖아 방법 중 하나는 (즉, 키보드 입력 시 에서 암호 암호 확인 기입란). 그러나, t # 39 는 원래 암호를 필드는 업데이트되도록 암호 확인 doesn& 되도륵 유효함.
내가 어떻게 할 수 있는 모든 것이 한 방법이 있는지, 2 개의 " 바인딩하면 ",?
난 다음 디렉티브을 싶어서 재 검증 여부에 관계없이 모두 입력 필드를 값 1 또는 2 값을 바뀌었다.
'use strict';
angular.module('myApp').directive('equals', function() {
return {
restrict: 'A', // only activate on element attribute
require: '?ngModel', // get a hold of NgModelController
link: function(scope, elem, attrs, ngModel) {
if(!ngModel) return; // do nothing if no ng-model
// watch own value and re-validate on change
scope.$watch(attrs.ngModel, function() {
validate();
});
// observe the other value and re-validate on change
attrs.$observe('equals', function (val) {
validate();
});
var validate = function() {
// values
var val1 = ngModel.$viewValue;
var val2 = attrs.equals;
// set validity
ngModel.$setValidity('equals', ! val1 || ! val2 || val1 === val2);
};
}
}
});
<input type="password" ng-model="value1" equals="{{value2}}" required>
<input type="password" ng-model="value2" equals="{{value1}}" required>
만들기 위한 별도의 디렉티브을 이 필요하지 않습니다. 이미 존재합니다 구축하십시오 각 UI 에서 암호 검증 도구. 이와 함께 할 수 있습니다.
<input name="password" required ng-model="password">
<input name="confirm_password"
ui-validate=" '$value==password' "
ui-validate-watch=" 'password' ">
Passwords match? {{!!form.confirm_password.$error.validator}}
이렇게 하면 해결할 수 있다.
<div ng-controller='Ctrl'>
<form name='form'>
<input data-ng-model='user.password' type="password" name='password' placeholder='password' required>
<div ng-show="form.password.$error.required">
Field required</div>
<input ng-model='user.password_verify' type="password" name='confirm_password' placeholder='confirm password' required data-password-verify="user.password">
<div ng-show="form.confirm_password.$error.required">
Field required!</div>
<div ng-show="form.confirm_password.$error.passwordVerify">
Fields are not equal!</div>
</form
</div>
var app = angular.module('myApp', []);
app.directive("passwordVerify", function() {
return {
require: "ngModel",
scope: {
passwordVerify: '='
},
link: function(scope, element, attrs, ctrl) {
scope.$watch(function() {
var combined;
if (scope.passwordVerify || ctrl.$viewValue) {
combined = scope.passwordVerify + '_' + ctrl.$viewValue;
}
return combined;
}, function(value) {
if (value) {
ctrl.$parsers.unshift(function(viewValue) {
var origin = scope.passwordVerify;
if (origin !== viewValue) {
ctrl.$setValidity("passwordVerify", false);
return undefined;
} else {
ctrl.$setValidity("passwordVerify", true);
return viewValue;
}
});
}
});
}
};
});
또 다른 한 모델을 다른 입력 값에 대한 입력입니다 일치시킵니다 여기있을 시행하십시오 있다.
app.directive('nxEqual', function() {
return {
require: 'ngModel',
link: function (scope, elem, attrs, model) {
if (!attrs.nxEqual) {
console.error('nxEqual expects a model as an argument!');
return;
}
scope.$watch(attrs.nxEqual, function (value) {
model.$setValidity('nxEqual', value === model.$viewValue);
});
model.$parsers.push(function (value) {
var isValid = value === scope.$eval(attrs.nxEqual);
model.$setValidity('nxEqual', isValid);
return isValid ? value : undefined;
});
}
};
});
따라서 '다음' 의 모델은 암호 기입란 로긴스파스워드 설정한 다음 속성에 대한 검증 상자: ',', '및' 포르마나메지에르메나미스 login.password" " nx 비유하 = $ 에로스터너스콸 테스트합니다. 같은 있습니다.
<form name="form">
<input type="password" ng-model="login.password">
<input type="password" ng-model="login.verify" nx-equal="login.password" name="verify">
<span ng-show="form.verify.$error.nxEqual">Must be equal!</span>
</form>
나의 새로운 프로젝트를 위해 부모한테 그들위에 수정하십시오 디렉티브을 도왔으매 것이다 ',' 네스콸 표시하십시오 경우에만, 이 때 오류가 모든검증 입력 값을 했다. 그렇지 않으면 네스콸 '오류' 무트 합니다. 다음은 확장 버전:
app.directive('nxEqualEx', function() {
return {
require: 'ngModel',
link: function (scope, elem, attrs, model) {
if (!attrs.nxEqualEx) {
console.error('nxEqualEx expects a model as an argument!');
return;
}
scope.$watch(attrs.nxEqualEx, function (value) {
// Only compare values if the second ctrl has a value.
if (model.$viewValue !== undefined && model.$viewValue !== '') {
model.$setValidity('nxEqualEx', value === model.$viewValue);
}
});
model.$parsers.push(function (value) {
// Mute the nxEqual error if the second ctrl is empty.
if (value === undefined || value === '') {
model.$setValidity('nxEqualEx', true);
return value;
}
var isValid = value === scope.$eval(attrs.nxEqualEx);
model.$setValidity('nxEqualEx', isValid);
return isValid ? value : undefined;
});
}
};
});
그리고 그것을 사용하는 것과 같은 있습니다.
<form name="form">
<input type="password" ng-model="login.password">
<input type="password" ng-model="login.verify" nx-equal-ex="login.password" name="verify">
<span ng-show="form.verify.$error.nxEqualEx">Must be equal!</span>
</form>
Try it.
I have done it 없이 전달했다.
<input type="password" ng-model="user.password" name="uPassword" required placeholder='Password' ng-minlength="3" ng-maxlength="15" title="3 to 15 characters" />
<span class="error" ng-show="form.uPassword.$dirty && form.uPassword.$error.minlength">Too short</span>
<span ng-show="form.uPassword.$dirty && form.uPassword.$error.required">Password required.</span><br />
<input type="password" ng-model="user.confirmpassword" name="ucPassword" required placeholder='Confirm Password' ng-minlength="3" ng-maxlength="15" title="3 to 15 characters" />
<span class="error" ng-show="form.ucPassword.$dirty && form.ucPassword.$error.minlength">Too short</span>
<span ng-show="form.ucPassword.$dirty && form.ucPassword.$error.required">Retype password.</span>
<div ng-show="(form.uPassword.$dirty && form.ucPassword.$dirty) && (user.password != user.confirmpassword)">
<span>Password mismatched</span>
</div>
좋은 인프라일까요 프로젝트 (https://github.com/wongatech/angular-confirm-field) 이.
여기 (예: http://wongatech.github.io/angular-confirm-field/
아래 코드는 2 입력 필드를 보여 주고 있는 구축됩니까 기능
<input ng-confirm-field ng-model="emailconfirm" confirm-against="email" name="my-email-confirm"/>
<input ng-model="email" name="my-email" />
Vmware. 쓸 수 있으므로, 각 1.3.0-beta12 잘못된 투입물 don& # 39, t, t # 39 영모델 can& 제스쳐놀이처럼 그리곤요 검증하십시오 여기서 알 수 있듯이. http://plnkr.co/edit/W6AFHF308nyKVMQ9vomw? p = 미리봅니다. 이를 위해 도입된 새로운 검사기를 파이프라인간의 및 첨부할 수 있는 이 같은 것입니다.
사실 그 노트, ve I& # 39 의 공통 컴포넌트 추가 검사기를 바워 만들었습니다. (https://github.com/intellix/angular-validators) 이 포함된.
angular.module('validators').directive('equals', function() {
return {
restrict: 'A',
require: '?ngModel',
link: function(scope, elem, attrs, ngModel)
{
if (!ngModel) return;
attrs.$observe('equals', function() {
ngModel.$validate();
});
ngModel.$validators.equals = function(value) {
return value === attrs.equals;
};
}
};
});
angular.module('validators').directive('notEquals', function() {
return {
restrict: 'A',
require: '?ngModel',
link: function(scope, elem, attrs, ngModel)
{
if (!ngModel) return;
attrs.$observe('notEquals', function() {
ngModel.$validate();
});
ngModel.$validators.notEquals = function(value) {
return value === attrs.notEquals;
};
}
};
});
.directive('sameAs', function() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
ctrl.$parsers.unshift(function(viewValue) {
if (viewValue === scope[attrs.sameAs]) {
ctrl.$setValidity('sameAs', true);
return viewValue;
} else {
ctrl.$setValidity('sameAs', false);
return undefined;
}
});
}
};
});
<input ... name="password" />
<input type="password" placeholder="Confirm Password"
name="password2" ng-model="password2" ng-minlength="9" same-as='password' required>
나는 이 같은 문제를 다루는 발견하여 좋은 블로그 포스트 그것에 대해 쓴 피오트르 부다. 이 과정은 매우 좋은 it& # 39 을 읽고 잘 했다고 설명했다. 이 코드는 다음과 같습니다.
directives.directive("repeatPassword", function() {
return {
require: "ngModel",
link: function(scope, elem, attrs, ctrl) {
var otherInput = elem.inheritedData("$formController")[attrs.repeatPassword];
ctrl.$parsers.push(function(value) {
if(value === otherInput.$viewValue) {
ctrl.$setValidity("repeat", true);
return value;
}
ctrl.$setValidity("repeat", false);
});
otherInput.$parsers.push(function(value) {
ctrl.$setValidity("repeat", value === ctrl.$viewValue);
return value;
});
}
};
});
그래서 뭔가 할 수 있는 것 같다.
<input type="password" name="repeatPassword" id="repeatPassword" placeholder="repeat password" ng-model="user.repeatPassword" repeat-password="password" required>
저자는 크레딧보다 마이그레이션된
두 개의 입력 필드를 찾기 위해 검증, 내가 가장 적합한 방법을 양식
app.directive('passwordVerify', function() {
return {
require: 'ngModel',
link: function (scope, elem, attrs, ctrl) {
if (!attrs.passwordVerify) {
return;
}
scope.$watch(attrs.passwordVerify, function (value) {
if( value === ctrl.$viewValue && value !== undefined) {
ctrl.$setValidity('passwordVerify', true);
ctrl.$setValidity("parse",undefined);
}
else {
ctrl.$setValidity('passwordVerify', false);
}
});
ctrl.$parsers.push(function (value) {
var isValid = value === scope.$eval(attrs.passwordVerify);
ctrl.$setValidity('passwordVerify', isValid);
return isValid ? value : undefined;
});
}
};
});
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="form-group" ng-class="{ 'has-error': form.password.$dirty && form.password.$error.required || (form.password.$error.minlength || form.password.$error.maxlength)}">
<input type="password" name="password" ng-minlength="6" ng-maxlength="16" id="password" class="form-control" placeholder="Password" ng-model="user.password" required />
<span ng-show="form.password.$dirty && form.password.$error.required" class="help-block">Password is required</span>
<span ng-show="form.password.$error.minlength || form.password.$error.maxlength" class="help-block">Password must be 6-16 character long</span>
</div>
</div>
</div>
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="form-group" ng-class="{ 'has-error': (form.confirm_password.$dirty && form.confirm_password.$error.required) || form.confirm_password.$error.passwordVerify }">
<input type="password" name="confirm_password" id="confirm_password" class="form-control" placeholder="Confirm Password" ng-model="user.confirm_password" required password-verify="user.password" />
<span ng-show="form.confirm_password.$dirty && form.confirm_password.$error.required" class="help-block">Confirm Password is required</span>
<span ng-show="form.confirm_password.$error.passwordVerify" class="help-block">Please make sure passwords match & must be 6-16 character long</span>
</div>
</div>
</div>
이 솔루션은 제공한 것과 유사한 $ 검사기를 및 is the one I like 도미닉 왓슨입니다 사용하는 것이 가장 좋습니다. 변화는 볼 수 있는 유일한 표현식에서는.
>. $ 검사기를 검사기를 때마다 적용되는 모음 >. 모델 값 변경. 키 값을 나타내는 오브젝트 내의 >. 반면 함수은) 은 검증 문법검사기 이름입니다. >. 역사는 고가화되어 있다. 모델 값을 검증 작업을 함께 제공됩니다. >. 그리고 진정한 또는 false 값을 인수로 따라 반품해야 합니다 >. 응답 iqn 검증
https://code.angularjs.org/1.3.15/docs/api/ng/type/ngModel.NgModelController 에서
angular.module('app').directive("passwordConfirm", function() {
"use strict";
return {
require : "ngModel",
restrict : "A",
scope : {
//We will be checking that our input is equals to this expression
passwordConfirm : '&'
},
link : function(scope, element, attrs, ctrl) {
//The actual validation
function passwordConfirmValidator(modelValue, viewValue) {
return modelValue == scope.passwordConfirm();
}
//Register the validaton when this input changes
ctrl.$validators.passwordConfirm = passwordConfirmValidator;
//Also validate when the expression changes
scope.$watch(scope.passwordConfirm, ctrl.$validate);
}
};
});
바로 사용할 수 있어
<input type="password" ng-model="user.password"/>
<input type="password" ng-model="user.confirmPassword"
password-confirm="user.password" />
아닌 게 아니라 다만 디렉티브입니다 솔루션이므로 working for me:
<input ng-model='user.password'
type="password"
name='password'
placeholder='password'
required>
<input ng-model='user.password_verify'
type="password"
name='confirm_password'
placeholder='confirm password'
ng-pattern="getPattern()"
required>
또한 컨트롤러:
//Escape the special chars
$scope.getPattern = function(){
return $scope.user.password &&
$scope.user.password.replace(/([.*+?^${}()|\[\]\/\\])/g, '\\$1');
}
http://plnkr.co/edit/QDTnipCsHdg56vgygsqC? p = 미리봅니다
이 작동 방법, 이는 모두 간단하고 명료하게 *
JavaScript *
var app = angular.module("app");
app.controller("SamePaswordController", function () {
this.password;
this.confirm;
this.save = function () {
alert("Saved!");
};
}
app.directive("match", function () {
return {
restrict:"A",
require:"ngModel",
link: function(scope, element, attrs, ctrl) {
function matchValidator(value) {
scope.$watch(attrs.match, function(newValue, oldValue) {
var isValid = value === scope.$eval(attrs.match);
ctrl.$setValidity('match', isValid);
});
return value;
}
ctrl.$parsers.push(matchValidator);
}
};
});
<form name="regForm" ng-controller="SamePaswordController as regCtrl"
ng-submit="regForm.$valid && regCtrl.save()" novalidate>
<input name="password" ng-model="regCtrl.password"
type="password" required placeholder="Password"/>
<input name="confirm" ng-model="regCtrl.confirm" match="regCtrl.password"
type="password" required placeholder="Confirm password"/>
<div> regForm is valid:{{regForm.$valid}}</div>
<input type="submit" value="Save"/>
</form>
이 예제를 사용하여 리포 복제할 수 있습니다 https://github.com/rogithub/roangularjs
다음은 이 문제에 대한 내 시행하십시오. 이 값을 비교하여 내시경이요 대신 디렉티브을 아니하였으매 양식
'use strict';
(function () {
angular.module('....').directive('equals', function ($timeout) {
return {
restrict: 'A',
require: ['^form', 'ngModel'],
scope: false,
link: function ($scope, elem, attrs, controllers) {
var validationKey = 'equals';
var form = controllers[0];
var ngModel = controllers[1];
if (!ngModel) {
return;
}
//run after view has rendered
$timeout(function(){
$scope.$watch(attrs.ngModel, validate);
$scope.$watch(form[attrs.equals], validate);
}, 0);
var validate = function () {
var value1 = ngModel.$viewValue;
var value2 = form[attrs.equals].$viewValue;
var validity = !value1 || !value2 || value1 === value2;
ngModel.$setValidity(validationKey, validity);
form[attrs.equals].$setValidity(validationKey,validity);
};
}
};
});
})();
지금) 은 html 에서 실제 양식 대신 범위지정 가치:
<form name="myForm">
<input type="text" name="value1" equals="value2">
<input type="text" name="value2" equals="value1">
<div ng-show="myForm.$invalid">The form is invalid!</div>
</form>
<input name="password" type="text" required="" ng-model="password" placeholder="password" class="ng-dirty ng-valid ng-valid-required">
<input name="confirm_password" type="text" required="" ng-model="confirm_password" ui-validate=" '$value==password' " ui-validate-watch=" 'password' " placeholder="confirm password" class="ng-dirty ng-valid-required ng-invalid ng-invalid-validator">
<span ng-show="form.confirm_password.$error.validator">Passwords do not match!</span>
password errors: {
"required": false,
"validator": true
}
이미 많은 수의 추가하려면 솔루션, 이 제대로 for me.
( 얀 라우스만 오토메이티드 중지함 최신값 작업 앙굴라이스 베타 버전 대비).
angular.module('myApp').directive('matchValidator', [function() {
return {
require: 'ngModel',
link: function(scope, elm, attr, ctrl) {
var pwdWidget = elm.inheritedData('$formController')[attr.matchValidator];
ctrl.$parsers.push(function(value) {
if (value === pwdWidget.$viewValue) {
ctrl.$setValidity('match', true);
return value;
}
if (value && pwdWidget.$viewValue) {
ctrl.$setValidity('match', false);
}
});
pwdWidget.$parsers.push(function(value) {
if (value && ctrl.$viewValue) {
ctrl.$setValidity('match', value === ctrl.$viewValue);
}
return value;
});
}
};
}])
<input type="email" ng-model="value1" name="email" required>
<input type="email" ng-model="value2" name="emailConfirm" match-validator="email" required>
<div ng-if="[[yourFormName]].emailConfirm.$error">
<div ng-if="[[yourFormName]].emailConfirm.$error.match">
Email addresses don't match.
</div>
</div>
이 협력했습니다 for me.
modulename.directive('passwordCheck', function () {
return {
restrict: 'A', // only activate on element attribute
require: '?ngModel', // get a hold of NgModelController
link: function (scope, elem, attrs, ngModel) {
if (!ngModel) return; // do nothing if no ng-model
var Value = null;
// watch own value and re-validate on change
scope.$watch(attrs.ngModel, function (val) {
Value = val;
validate();
});
// observe the other value and re-validate on change
attrs.$observe('passwordCheck', function () {
validate();
});
var validate = function () {
// values
var val1 = Value;
var val2 = attrs.passwordCheck;
// set validity
if (val1 != '' && val1 != undefined) {
ngModel.$setValidity('passwordCheck', val1 == val2);
}
else {
ngModel.$setValidity('passwordCheck', true);
}
};
}
}
});
ng-model="confirmpassword.selected" type="password" name="confirmpassword"
password-check="{{password.selected}}"
ng-show="resetpasswordform.confirmpassword.$error.passwordCheck && submitted" Password does not match
내가 어렸을 때, 내가 내 스스로 하는 동일한 문제가 경식도 구축하십시오 디렉티브을 고정식입니다 대체하십시오 추가
>. 'ctrl' (), $ 검증하십시오.
여기서 ctrl is my 영모델콘트로예르
this is my view
<input type="password" match="signupCtrl.registrationData.password" name="confirmPassword" class="form-control" placeholder="Confirm Password" data-ng-model="signupCtrl.registrationData.confirmPassword" required>
<span ng-messages="registerForm.confirmPassword.$error">
<span ng-message="match">The Password must match</span>
</span>
이건 내 디렉티브을
(function () {
'use strict';
angular.module('matchDirective', [
// Angular modules
// Custom modules
// 3rd Party Modules
]);
})();
(function () {
'use strict';
angular
.module('matchDirective')
.directive('match', match);
match.$inject = ['$window'];
function match($window) {
// Usage:
// <element match="source"></element>
// Creates:
//
var directive = {
link: link,
restrict: 'A',
require: 'ngModel',
};
return directive;
function link(scope, element, attrs, ctrl) {
scope.$watch(attrs['match'], function (newVal, oldVal) {
ctrl.$validators.match = function (modelValue, viewValue) {
if (newVal == modelValue) {
return true;
} else {
return false;
}
}
ctrl.$validate();
});
}
}
})();
Keep It Simple 및 멍청한 (키스) 이 한 게 도움이 될 것입니다. 더 빠르고 쉽게 다음과 같이 해당되어서는 비밀번호란 모두 여부를 확인할 수 있다.
<div ng-app="app" ng-controller="passwordCheck">
<form name="signUp" ng-submit="submitForm()" novalidate>
<input type="password" name="password" ng-model="password" required>
<input type="password" name="ConfirmPassword" ng-model="passwordconfirm" required>
<button type="submit"> Submit</button>
</form>
<hr>
<span>Do they match?</span> {{signUp.password.$viewValue == signUp.confirmPassword.$viewValue}}
</div>
그리고 이 양식을 제출하기 전에, 할 수 있는 너회의 js
var app = angular.module("app", []);
app.controller("passwordCheck", function($scope) {
$scope.submitForm = function() {
if ($scope.signUp.$valid && $scope.signUp.password.$viewValue == $scope.signUp.confirmPassword.$viewValue) {
alert('Its a match!');
};
};
});
[이스피들] [1] 뿐만 아니라 그 테스트할 수 있습니다.