我有一个表单需要验证。
表单包含很多部分,其中一些部分默认是禁用的。每个字段中的值都是正确的,但它违反了我的验证指令。例如,当它禁用时它应该包含 0,但当它可编辑时它应该包含其他内容。不管怎样,我给它们附加了一个禁用指令,然后把它们放下。
当我提交表单时(使用 Angular 范围函数),if ($scope.sarfaslForm.$invalid) --> 返回 true。当我检查 $scope.sarfaslForm.$error 列表时,它说我有两个无效字段。
在这篇博客之后,我实现了我的验证: http://blog.yodersolutions.com/bootstrap-form-validation-done-right-in-angularjs/
并关注this thread ,我创建了一个指令来忽略我禁用的一些控件:
我对这个指令做了一个小改动:
.directive('hsDisableValidation', function() {
return {
require: '^form',
restrict: 'A',
link: function(scope, element, attrs,form) {
var control;
scope.$watch(function() {
return scope.$eval(attrs.hsDisableValidation);
}, function(value) {
if (!control) {
control = form[element[0].name];
//form[element.find("input").attr("name")];
}
if (value === false) {
form.$addControl(control);
angular.forEach(control.$error, function(validity, validationToken) {
form.$setValidity(validationToken, !validity, control);
});
} else {
form.$removeControl(control);
//In Here: I tried to $setValidity of controls to true, Remove Error List, and Remove Validator Function, but these things didn't worked out
}
});
}
}
})
这里的验证对我来说总是失败: PS:因为我在“文本”类型的字段上使用它,所以我没有最小/最大值,只有最小/最大长度。我确定这不是问题所在,但我包含此代码以确保安全。
.directive('hsMinValue', function() {
return {
require: 'ngModel',
link: function (scope, elem, attr, ngModel) {
function isLesser(value) {
var minVal = parseInt(attr.hsMinValue);
return parseInt(value) < minVal;
}
function validate(value) {
var valid = !isLesser(value);
ngModel.$setValidity('minValue', valid);
return valid ? value : undefined;
}
ngModel.$parsers.unshift(function (value) {
ngModel.$setValidity('minValue', !isLesser(value));
return value;
});
ngModel.$formatters.unshift(function (value) {
ngModel.$setValidity('minValue', !isLesser(value));
return value;
});
}
}
});
然后我保存:
saveSarfasl: function () {
$scope.$broadcast('show-errors-check-validity');
if ($scope.sarfaslForm.$invalid) { --> True :|
return;
}
//Stuffs
}
编辑:应 James 的要求,我将 HTML 放在 并在此处查看我的页面。
<div class="clearfix">
<form name="sarfaslForm" novalidate>
<table class="table-condensed">
<tbody>
<tr>
<td>
کد سرفصل
</td>
<td>
<table class="table-condensed">
<tbody>
<tr>
<td data-ng-if="View.FinYear.LenK != 0">
کل
</td>
<td data-ng-if="View.FinYear.LenM != 0">
معین
</td>
<td data-ng-if="View.FinYear.LenT1 != 0">
تفضیل یک
</td>
<td data-ng-if="View.FinYear.LenT2 != 0">
تفضیل دو
</td>
<td data-ng-if="View.FinYear.LenJ != 0">
جزء
</td>
</tr>
<tr>
<td data-ng-if="View.FinYear.LenK != 0">
<div class="form-group" hs-show-errors hs-show-success>
<input name="CodKol" type="text" hs-restrict-pattern="[^\d]*" maxlength="{{View.FinYear.LenK}}"
class="form-control input-sm"
data-ng-model="View.Kol" data-ng-disabled="View.Level!==1"
data-ng-blur="Events.codeChanged('k')"
data-ng-change="Events.setSarfaslCod()"
hs-disable-validation="View.Level!==1"
data-ng-required="true"
hs-min-value="1" />
<p class="help-block" ng-if="sarfaslForm.CodKol.$error.required">
کد کل الظامی می باشد
</p>
<p class="help-block" ng-if="sarfaslForm.CodKol.$error.minValue">
کد کل نمی تواند صفر باشد
</p>
</div>
</td>
<td data-ng-if="View.FinYear.LenM != 0">
<div class="form-group" hs-show-errors hs-show-success>
<input name="CodMoin" type="text" hs-restrict-pattern="[^\d]*" maxlength="{{View.FinYear.LenM}}"
class="form-control input-sm"
data-ng-model="View.Moin" data-ng-disabled="View.Level!==2"
data-ng-blur="Events.codeChanged('m')"
data-ng-change="Events.setSarfaslCod()"
hs-disable-validation="View.Level!==2"
data-ng-required
hs-min-value="1" />
<p class="help-block" ng-if="sarfaslForm.CodMoin.$error.required">
کد معین الظامی می باشد
</p>
<p class="help-block" ng-if="sarfaslForm.CodMoin.$error.minValue">
کد معین نمی تواند صفر باشد
</p>
</div>
</td>
<td data-ng-if="View.FinYear.LenT1 != 0">
<div class="form-group" hs-show-errors hs-show-success>
<input name="CodTafzil1" type="text" hs-restrict-pattern="[^\d]*" maxlength="{{View.FinYear.LenT1}}"
class="form-control input-sm"
data-ng-model="View.Tafzil1" data-ng-disabled="View.Level!==3"
data-ng-blur="Events.codeChanged('t1')"
data-ng-change="Events.setSarfaslCod()"
hs-disable-validation="View.Level!==3"
data-ng-required
hs-min-value="1" />
<p class="help-block" ng-if="sarfaslForm.CodTafzil1.$error.required">
کد تفظیل یک الظامی می باشد
</p>
<p class="help-block" ng-if="sarfaslForm.CodTafzil1.$error.minValue">
کد تفظیل یک نمی تواند صفر باشد
</p>
</div>
</td>
<td data-ng-if="View.FinYear.LenT2 != 0">
<div class="form-group" hs-show-errors hs-show-success>
<input name="CodTafzil2" type="text" hs-restrict-pattern="[^\d]*" maxlength="{{View.FinYear.LenT2}}"
class="form-control input-sm"
data-ng-model="View.Tafzil2" data-ng-disabled="View.Level!==4"
data-ng-blur="Events.codeChanged('t2')"
data-ng-change="Events.setSarfaslCod()"
hs-disable-validation="View.Level!==4"
data-ng-required
hs-min-value="1" />
<p class="help-block" ng-if="sarfaslForm.CodTafzil2.$error.required">
کد تفظیل دو الظامی می باشد
</p>
<p class="help-block" ng-if="sarfaslForm.CodTafzil2.$error.minValue">
کد تفظیل دو نمی تواند صفر باشد
</p>
</div>
</td>
<td data-ng-if="View.FinYear.LenJ != 0">
<div class="form-group" hs-show-errors hs-show-success>
<input name="CodJoz" type="text" hs-restrict-pattern="[^\d]*" maxlength="{{View.FinYear.LenJ}}"
class="form-control input-sm"
data-ng-model="View.Joz" data-ng-disabled="View.Level!==5"
data-ng-blur="Events.codeChanged('j')"
data-ng-change="Events.setSarfaslCod()"
hs-disable-validation="View.Level!==5"
data-ng-required
hs-min-value="1" />
<p class="help-block" ng-if="sarfaslForm.CodJoz.$error.required">
کد جزء الظامی می باشد
</p>
<p class="help-block" ng-if="sarfaslForm.CodJoz.$error.minValue">
کد جزء نمی تواند صفر باشد
</p>
</div>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr>
<td>
عنوان سرفصل
</td>
<td ng-class="{'has-error':sarfaslForm.HsbNam.$invalid && sarfaslForm.HsbNam.$dirty}">
<div class="form-group" hs-show-errors hs-show-success>
<input name="HsbNam" type="text" data-ng-model="View.Sarfasl.HsbNam"
class="form-control input-sm"
data-ng-required="true" />
<p class="help-block" ng-if="sarfaslForm.HsbNam.$error.required">
نام سرفصل الظامی می باشد
</p>
</div>
</td>
</tr>
<tr>
<td>
</td>
<td>
<div class="radio" hs-show-errors>
<label class="control-label">
<input type="radio" data-ng-model="View.Sarfasl.HsbKind" name="HsbKind" data-ng-value="'00'"
data-ng-required="true" />
زیر سطح دارد
</label>
</div>
<div class="radio" hs-show-errors>
<label class="control-label">
<input type="radio" data-ng-model="View.Sarfasl.HsbKind" name="HsbKind" data-ng-value="'11'"
data-ng-required="true" />
سطح آخر است
</label>
<p class="help-block" ng-if="sarfaslForm.HsbKind.$error.required">
انتخاب یکی از حالات الظامی می باشد
</p>
</div>
</td>
</tr>
<tr>
<td>
</td>
<td>
<div class="radio" hs-show-errors>
<label class="control-label">
<input type="radio" data-ng-model="View.Sarfasl.Permanent" name="Permanent" data-ng-value="'1'"
data-ng-required="true" />
حساب دائم
</label>
</div>
<div class="radio" hs-show-errors>
<label class="control-label">
<input type="radio" data-ng-model="View.Sarfasl.Permanent" name="Permanent" data-ng-value="'0'"
data-ng-required="true" />
حساب موقت
</label>
<p class="help-block" ng-if="sarfaslForm.Permanent.$error.required">
انتخاب یکی از حالات الظامی می باشد
</p>
</div>
</td>
</tr>
<tr>
<td>
</td>
<td>
<div class="radio" hs-show-errors>
<label class="control-label">
<input type="radio" data-ng-model="View.Sarfasl.AccessFlag" name="AccessFlag" data-ng-value="0"
data-ng-required="true" />
حساب برای همه در دسترس باشد
</label>
</div>
<div class="radio" hs-show-errors>
<label class="control-label">
<input type="radio" data-ng-model="View.Sarfasl.AccessFlag" name="AccessFlag" data-ng-value="1"
data-ng-required="true" />
حساب فقط برای کاربران زیر در دسترس باید
</label>
<p class="help-block" ng-if="sarfaslForm.AccessFlag.$error.required">
انتخاب یکی از حالات الظامی می باشد
</p>
</div>
</td>
</tr>
<tr data-ng-if="View.Sarfasl.AccessFlag==1">
<td>
</td>
<td>
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>
</th>
<th>
کاربران
</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="user in View.UserList">
<td>
<div class="checkbox">
<label class="control-label">
<input type="checkbox" data-ng-model="user.Checked" data-ng-click="Events.userChecking(user)" />
</label>
</div>
</td>
<td>
{{user.UserID}}
</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr>
<td>
</td>
<td>
<!-- Hsb Types -->
<div class="checkbox">
<label class="control-label">
<input type="checkbox" data-ng-model="View.CheckBoxAllowRegisterLiability"
data-ng-click="Events.hsbTypeChecking(View.HsbTypes.AllowRegisterLiability, View.CheckBoxAllowRegisterLiability)" />
اجازه ثبت بدهکاری در اسناد داشته باشد
</label>
</div>
<div class="checkbox">
<label class="control-label">
<input type="checkbox" data-ng-model="View.CheckBoxAllowRegisterCredits"
data-ng-click="Events.hsbTypeChecking(View.HsbTypes.AllowRegisterCredits, View.CheckBoxAllowRegisterCredits)" />
اجازه ثبت بستانکاری در اسناد داشته باشد
</label>
</div>
<div class="checkbox">
<label class="control-label">
<input type="checkbox" data-ng-model="View.CheckBoxReminderShouldOnlyBeDebtor"
data-ng-click="Events.hsbTypeChecking(View.HsbTypes.ReminderShouldOnlyBeDebtor, View.CheckBoxReminderShouldOnlyBeDebtor)" />
مانده حساب فقط باید بدهکار باشد
</label>
</div>
<div class="checkbox">
<label class="control-label">
<input type="checkbox" data-ng-model="View.CheckBoxReminderShouldOnlyBeCreditor"
data-ng-click="Events.hsbTypeChecking(View.HsbTypes.ReminderShouldOnlyBeCreditor, View.CheckBoxReminderShouldOnlyBeCreditor)" />
مانده حساب فقط باید بستانکار باشد
</label>
</div>
</td>
</tr>
<tr>
<td>
یادداشت
</td>
<td>
<textarea data-ng-model="View.Sarfasl.YadDasht" cols="200" rows="4" class="form-control input-sm">
</textarea>
</td>
</tr>
<tr>
<td>
</td>
<td>
<button type="button" class="btn btn-sm btn-primary" data-ng-click="Events.saveSarfasl()">
ذخیره اطلاعات
</button>
<a href="/#/Sarfasl" class="btn btn-sm btn-primary">
بازگشت
</a>
</td>
</tr>
</tbody>
</table>
</form>
</div>
当我使用它时,所有控件都能很好地单独查看每个控件。
但是在我的函数中提交(提交按钮是普通按钮,没有效果,而是调用我的函数)之后,我看到总体结果有错误:
$scope.sarfaslForm.$invalid ==> true
最佳答案
好的,这是您的代码所做的假设。当您查看以检查验证时,您正在检查是否 value === false 否则您将其添加到您的表单中,这不是您想要描述的逻辑。
您要说明的是,如果字段被禁用并设置为 0,无论值如何,我都希望它从表单中删除,然后如果值为 false 我希望它从表单中删除,否则验证表单。只需进行逻辑检查以查看该字段是否被禁用并将其从验证中删除。
if (value === 0) {
form.$removeControl(control);
} else if (value === false) {
form.$addControl(control);
angular.forEach(control.$error, function(validity, validationToken) {
form.$setValidity(validationToken, !validity, control);
});
} else {
form.$removeControl(control);
}
关于javascript - 在 AngularJS 中禁用不需要的验证(条件验证),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32052991/
当我使用Bundler时,是否需要在我的Gemfile中将其列为依赖项?毕竟,我的代码中有些地方需要它。例如,当我进行Bundler设置时:require"bundler/setup" 最佳答案 没有。您可以尝试,但首先您必须用鞋带将自己抬离地面。 关于ruby-我需要将Bundler本身添加到Gemfile中吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/4758609/
给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru
我想安装一个带有一些身份验证的私有(private)Rubygem服务器。我希望能够使用公共(public)Ubuntu服务器托管内部gem。我读到了http://docs.rubygems.org/read/chapter/18.但是那个没有身份验证-如我所见。然后我读到了https://github.com/cwninja/geminabox.但是当我使用基本身份验证(他们在他们的Wiki中有)时,它会提示从我的服务器获取源。所以。如何制作带有身份验证的私有(private)Rubygem服务器?这是不可能的吗?谢谢。编辑:Geminabox问题。我尝试“捆绑”以安装新的gem..
我希望我的UserPrice模型的属性在它们为空或不验证数值时默认为0。这些属性是tax_rate、shipping_cost和price。classCreateUserPrices8,:scale=>2t.decimal:tax_rate,:precision=>8,:scale=>2t.decimal:shipping_cost,:precision=>8,:scale=>2endendend起初,我将所有3列的:default=>0放在表格中,但我不想要这样,因为它已经填充了字段,我想使用占位符。这是我的UserPrice模型:classUserPrice回答before_val
我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss
我注意到像bundler这样的项目在每个specfile中执行requirespec_helper我还注意到rspec使用选项--require,它允许您在引导rspec时要求一个文件。您还可以将其添加到.rspec文件中,因此只要您运行不带参数的rspec就会添加它。使用上述方法有什么缺点可以解释为什么像bundler这样的项目选择在每个规范文件中都需要spec_helper吗? 最佳答案 我不在Bundler上工作,所以我不能直接谈论他们的做法。并非所有项目都checkin.rspec文件。原因是这个文件,通常按照当前的惯例,只
我实际上是在尝试使用RVM在我的OSX10.7.5上更新ruby,并在输入以下命令后:rvminstallruby我得到了以下回复:Searchingforbinaryrubies,thismighttakesometime.Checkingrequirementsforosx.Installingrequirementsforosx.Updatingsystem.......Errorrunning'requirements_osx_brew_update_systemruby-2.0.0-p247',pleaseread/Users/username/.rvm/log/138121
我有一些非常大的模型,我必须将它们迁移到最新版本的Rails。这些模型有相当多的验证(User有大约50个验证)。是否可以将所有这些验证移动到另一个文件中?说app/models/validations/user_validations.rb。如果可以,有人可以提供示例吗? 最佳答案 您可以为此使用关注点:#app/models/validations/user_validations.rbrequire'active_support/concern'moduleUserValidationsextendActiveSupport:
当我的预订模型通过rake任务在状态机上转换时,我试图找出如何跳过对ActiveRecord对象的特定实例的验证。我想在reservation.close时跳过所有验证!叫做。希望调用reservation.close!(:validate=>false)之类的东西。仅供引用,我们正在使用https://github.com/pluginaweek/state_machine用于状态机。这是我的预订模型的示例。classReservation["requested","negotiating","approved"])}state_machine:initial=>'requested
我有一个服务模型/表及其注册表。在表单中,我几乎拥有服务的所有字段,但我想在验证服务对象之前自动设置其中一些值。示例:--服务Controller#创建Action:defcreate@service=Service.new@service_form=ServiceFormObject.new(@service)@service_form.validate(params[:service_form_object])and@service_form.saverespond_with(@service_form,location:admin_services_path)end在验证@ser