验证IP的指令:PORT
myApp.directive("validateServerAddress", ['input', function (input) {
var linker = function (scope, element, attrs) {
alert('Tese');
var parts = input.split(":");
var ip = parts[0].split(".");
var port = parts[1];
return validateNum(port, 1, 65535) &&
ip.length == 4 &&
ip.every(function (segment) {
return validateNum(segment, 0, 255);
});
scope.validateNum = function(input, min, max) {
var num = +input;
return num >= min && num <= max && input === num.toString();
}
};
return {
restrict: "EA",
link: linker
};
}]);
HTML输入
<div class="input-group">
<input type="text" validate-serveraddress placeholder="255.255.255.255:5000" name="serveraddress" id="serveraddress" class="color-tooltip form-control" ng-model="serveraddress" required>
</div>
在用户键入有效的IP:PORT地址之前,我需要显示自定义错误消息“无效的服务器地址”。该指令运作良好。可以使用下面的代码并且可以应用自定义类,但是我需要像所需字段的bootstrap显示一样显示消息。
document.querySelector("input").oninput = function (e) {
this.className = validateIpAndPort(this.value) ? "" : "invalid";
}
.invalid {
color: red;
}
如何使用 ngMessages 通过指令显示自定义验证,如下图所示?
答案 0 :(得分:0)
验证ip:我为你创建的端口的快速指令
app.directive("validateAddressPort", function() {
function validateIpAndPort(input) {
var parts = input.split(":");
var ip = parts[0].split(".");
var port = parts[1];
return validateNum(port, 1, 65535) &&
ip.length == 4 &&
ip.every(function (segment) {
return validateNum(segment, 0, 255);
});
}
function validateNum(input, min, max) {
var num = +input;
return num >= min && num <= max && input === num.toString();
}
return {
restrict: "A",
require: "ngModel",
link: function(scope, element, attributes, ngModel) {
ngModel.$validators.invalidaddressport = function(input) {
if(!input) {
return false;
}
return validateIpAndPort(input);
}
}
};
});
HTML:
<form name="myForm">
<div class="input-group">
<input type="text" ng-model="serveraddress" validate-address-port placeholder="255.255.255.255:5000" name="serveraddress" id="serveraddress" class="color-tooltip form-control" ng-model="serveraddress" required>
</div>
</form>
现在,您可以使用ngMessages,如:
<div ng-messages="myForm.serveraddress.$error" style="color:red" role="alert">
<div ng-message="required">You did not enter a field</div>
<div ng-message="invalidaddressport">Invalid Address:port</div>
</div>