【发布时间】:2015-01-02 20:00:38
【问题描述】:
我们正在开发一个网站,让产品经理可以保存和创建产品。
保存对输入的任何数据进行一些基本验证。 创建/发布具有所有验证,包括所需的数据检查。
有没有一种好方法可以对一个表单进行两种不同类型的验证?
以下是我尝试过的几种方法:
ng-必需
<input type="text" name="planName" ng-model="vm.product.planName" ng-required="vm.publishAttempt" />
我们的保存将表单标记为原始。
function saveSuccess()
{
vm.editForm.$setPristine();
vm.publishAttempt = false;
vm.isLoading = false;
}
这使得带有 ng-required 的表单输入在单击发布按钮时不会触发验证,并且设置了一个真值来验证它们。我看到的唯一解决方案是循环表单元素并将它们标记为脏。不过,这似乎是错误的方法。
function publish()
{
vm.isLoading = true;
vm.publishAttempt = true;
angular.forEach(vm.editForm, function (field)
{
if (field && field.$pristine != null)
{
console.log(field);
field.$setDirty();
}
});
setTimeout(function()
{
if (vm.editForm.$invalid)
{
vm.isLoading = false;
logger.error('Required data is missing. Please check the form and try again.');
}
else
{
if ($window.confirm('Are you sure you want to publish this product? Doing so will make this product available to everyone and any changes going forward will be considered corrections to the product. '))
{
productService.publishProduct($routeParams.productId)
.then(publishSuccess, publishFail);
}
else
{
vm.isLoading = false;
vm.publishAttempt = false;
}
}
}, 1000);
}
使用 fluentvalidation 进行后端验证
我们还使用 FluentValidation 进行后端验证。我已经尝试返回这些结果,但随后必须遍历所有结果并在表单上找到值并将其标记为无效。
function publishSuccess(result)
{
if (!result.IsValid)
{
angular.forEach(result.errors, function(error)
{
// Map error back to input and set invalid.
});
}
else
{
openDetail($routeParams.productId);
}
vm.isLoading = false;
}
默认使用 jQuery 作为解决方案非常诱人,但必须有一种我只是缺少的 AngularJS 方式。
我对 Angular 还很陌生,我是否遗漏了任何明显的东西?
【问题讨论】:
标签: angularjs forms validation