Javascript 在angular中,定制表单验证的好策略是什么?
随着我的应用程序的发展,我发现越来越需要更有效的表单验证。我个人不喜欢对字段更改进行评估的角度内置验证。而且总有一些事情是它无法解释的,比如验证youtube视频id是否有效。目前,我正在每个表单控制器中进行验证。我有一个类似这样的函数。每个字段都有一条消息,如果出现错误,消息将使用ng类显示为红色Javascript 在angular中,定制表单验证的好策略是什么?,javascript,angularjs,validation,Javascript,Angularjs,Validation,随着我的应用程序的发展,我发现越来越需要更有效的表单验证。我个人不喜欢对字段更改进行评估的角度内置验证。而且总有一些事情是它无法解释的,比如验证youtube视频id是否有效。目前,我正在每个表单控制器中进行验证。我有一个类似这样的函数。每个字段都有一条消息,如果出现错误,消息将使用ng类显示为红色 $scope.validate = function (callback) { // reset default messages setMessages(); // c
$scope.validate = function (callback) {
// reset default messages
setMessages();
// create shorter references
var item = $scope.item,
message = $scope.itemMessage;
// title exists
if (item.title === '') {
message.title.message = 'You must give your item a title.';
message.title.error = true;
message.errors += 1;
}
// extract and clear video id with youtube api
if ($scope.temp.video !== undefined && $scope.temp.video !== '') {
var id = '';
var url = $scope.temp.video.replace(/(>|<)/gi,'').split(/(vi\/|v=|\/v\/|youtu\.be\/|\/embed\/)/);
if(url[2] !== undefined) {
id = url[2].split(/[^0-9a-z_]/i);
id = id[0];
} else {
id = url;
}
$http.get("http://gdata.youtube.com/feeds/api/videos/" + id)
.then(function (res) {
$scope.item.video = id;
}, function (res) {
message.video.message = 'That is not a valid youtube video.';
message.video.error = true;
message.errors += 1;
$scope.item.video = '';
});
}
if (message.errors === 0) {
callback();
}
};
然后我的实际表单提交函数调用$scope.validate;将包含$http.post的函数传递给它。我看到的两个主要问题是,我的回调函数不是promise base,因此不能保证在出现错误时不会调用它,我已经一遍又一遍地阅读,以将大块逻辑保留在控制器之外。我还没有找到很好的例子来说明如何进行验证,但这肯定是一个常见的问题。您仍然可以使用Angular的内置验证,除非提交表单,否则不会对其进行评估: 基本上,在提交表单时设置$scope.submitted=true,并设置条件检查,以便仅在设置$scope.submitted时显示错误消息和类