目前这是我的代码:
<!doctype html>
<html ng-app="validation-example">
<head>
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
<link href="http://docs.angularjs.org/css/bootstrap.min.css" rel="stylesheet" />
<link href="http://docs.angularjs.org/css/font-awesome.css" rel="stylesheet" />
<link href="http://docs.angularjs.org/css/docs.css" rel="stylesheet" />
<link href="StyleSheet.css" rel="stylesheet" />
<script src="script.js"></script>
</head>
<body style="background-color: teal">
<link href="StyleSheet.css" rel="stylesheet" />
<div ng-controller="Controller">
<form name="form" class="css-form" novalidate>
Float:
<input type="text" ng-model="length" name="length" smart-float />
{{length}}<br />
<span ng-show="form.length.$error.float">This is not a valid float number!</span>
<br />
<button ng-click="submit()"
ng-disabled="form.$invalid">
Submit</button>
</form>
</div>
</body>
</html>
还有js
var app = angular.module('validation-example', []);
function Controller($scope) {
$scope.master = {};
$scope.reset = function () {
$scope.user = angular.copy($scope.master);
};
$scope.reset();
$scope.submit = function () {
debugger;
if (form.$invalid)
{
alert("sss");
}
};
}
var FLOAT_REGEXP = /^\d+((\.|\,)\d+)?$/;
app.directive('smartFloat', function () {
return {
require: 'ngModel',
link: function (scope, elm, attrs, ctrl) {
ctrl.$parsers.unshift(function (viewValue) {
if (FLOAT_REGEXP.test(viewValue)) {
ctrl.$setValidity('float', true);
return parseFloat(viewValue.replace(',', '.'));
} else {
ctrl.$setValidity('float', false);
return undefined;
}
});
}
};
});
当 float 无效时,我禁用了按钮。但是,我希望始终启用提交按钮,并在服务器上的函数中检查表单是否无效,并向用户发出警告,告知用户提交因数据无效而被中断。应用类绑定(bind)时,我可以“form.$invalid”,但如果我删除它以允许无效提交,则在函数中 if (form.$invalid) 未定义。如果表单中的输入无效,如何检查 Controller ?我可以循环遍历元素并检查 ng-invalid css 类,但这是最愚蠢的想法,所以请建议一个聪明的解决方案。
最佳答案
表单的所有错误都设置为 $scope.formName.$error
对象。我刚刚使用 Chrome 的开发者工具检查了为此对象设置的属性,发现该对象根据错误类型将所有验证错误保存在不同的数组中。下面的屏幕截图将为您提供更好的想法:
我检查此问题所使用的示例代码可在 jsfiddle 上找到。
您需要循环访问这些属性并构建您希望在弹出窗口上显示的错误消息。
关于validation - javascript 的 angular.js 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16913639/