[英]Custom form validation in AngularJS
我创建了一个自定义指令来验证“域名”名称表单字段。
表单字段元素为
<input type="text" autofocus name="domain" ng-model="user.domain" domain-validate="/^[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/" >
自定义指令代码为
app.directive('domainValidate', function() {
return {
// element must have ng-model attribute.
require: 'ngModel',
// scope = the parent scope
// elem = the element the directive is on
// attr = a dictionary of attributes on the element
// ctrl = the controller for ngModel.
link: function(scope, elem, attr, ctrl) {
//get the regex flags from the regex-validate-flags="" attribute (optional)
var flags = attr.domainValidateFlags || 'i';
// create the regex obj.
var regex = new RegExp(attr.domainValidate, flags);
// add a parser that will process each time the value is
// parsed into the model when the user updates it.
ctrl.$parsers.unshift(function(value) {
// test and set the validity after update.
var valid = regex.test(value);
ctrl.$setValidity('domainValidate', valid);
// if it's valid, return the value to the model,
// otherwise return undefined.
return valid ? value : undefined;
});
// add a formatter that will process each time the value
// is updated on the DOM element.
ctrl.$formatters.unshift(function(value) {
// validate.
console.log(value)
ctrl.$setValidity('domainValidate', regex.test(value));
// return the value or nothing will be written to the DOM.
return value;
});
}
};
});
我想验证表单提交以及值更改上的字段。
上面的代码无法正常工作,请任何人帮我解决上面代码中的错误或让我知道如何验证域名字段
谢谢
老式的帖子,我对新手不满意,但是尝试一下
<form name="userForm" ng-submit="submit()" novalidate>
<div>
<input type="text" autofocus name="domain" ng-model="user.domain" domain-validate="^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,63}$" required>
<div ng-show="userForm.domain.$error.domainValidate">invalid domain</div>
<div ng-show="userForm.domain.$dirty && userForm.domain.$error.required">required</div>
</div>
<button type="submit">Submit</button>
</form>
然后js指令
app.directive('domainValidate', function () {
return {
require: 'ngModel',
link: function (scope, elem, attr, ctrl) {
//get the regex flags from the regex-validate-flags="" attribute (optional)
var flags = attr.domainValidateFlags || 'i';
// create the regex obj.
var regex = new RegExp(attr.domainValidate, flags);
function setValidity(value) {
ctrl.$setValidity('domainValidate', regex.test(value));
}
scope.$watch(attr.ngModel, function (newValue, oldValue) {
if (newValue !== undefined && newValue !== oldValue) {
setValidity(newValue);
}
});
scope.submit = function () {
setValidity(ctrl.$modelValue);
for (var error in ctrl.$error) {
if (ctrl.$error[error]) return;
}
// send stuff
}
}
};
});
我的建议是:代替自定义指令验证,请使用默认URL验证:
<input type="url" autofocus name="domain" ng-model="user.domain">
或者,如果您不想使用它,请在小提琴中共享您的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.