Gio*_*zas 29 c# jquery jquery-validate unobtrusive-validation asp.net-mvc-4
我在互联网上关注了一些文章和教程,以便创建一个自定义验证属性,该属性也支持asp.net mvc 4网站中的客户端验证.这就是我现在所拥有的:
RequiredIfAttribute.cs
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)] //Added
public class RequiredIfAttribute : ValidationAttribute, IClientValidatable
{
private readonly string condition;
private string propertyName; //Added
public RequiredIfAttribute(string condition)
{
this.condition = condition;
this.propertyName = propertyName; //Added
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
PropertyInfo propertyInfo = validationContext.ObjectType.GetProperty(this.propertyName); //Added
Delegate conditionFunction = CreateExpression(validationContext.ObjectType, _condition);
bool conditionMet = (bool)conditionFunction.DynamicInvoke(validationContext.ObjectInstance);
if (conditionMet)
{
if (value == null)
{
return new ValidationResult(FormatErrorMessage(null));
}
}
return ValidationResult.Success;
}
private Delegate CreateExpression(Type objectType, string expression)
{
LambdaExpression lambdaExpression = System.Linq.Dynamic.DynamicExpression.ParseLambda(objectType, typeof(bool), expression); //Added
Delegate function = lambdaExpression.Compile();
return function;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var modelClientValidationRule = new ModelClientValidationRule
{
ValidationType = "requiredif",
ErrorMessage = ErrorMessage //Added
};
modelClientValidationRule.ValidationParameters.Add("param", this.propertyName); //Added
return new List<ModelClientValidationRule> { modelClientValidationRule };
}
}
Run Code Online (Sandbox Code Playgroud)
然后我将此属性应用于这样的类的属性
[RequiredIf("InAppPurchase == true", "InAppPurchase", ErrorMessage = "Please enter an in app purchase promotional price")] //Added "InAppPurchase"
public string InAppPurchasePromotionalPrice { get; set; }
public bool InAppPurchase { get; set; }
Run Code Online (Sandbox Code Playgroud)
所以我想要做的是显示一条错误消息,当InAppPurchase字段为true(表示在表单中检查)时,需要字段InAppPurchasePromotionalPrice.以下是视图的相关代码:
<div class="control-group">
<label class="control-label" for="InAppPurchase">Does your app include In App Purchase?</label>
<div class="controls">
@Html.CheckBoxFor(o => o.InAppPurchase)
@Html.LabelFor(o => o.InAppPurchase, "Yes")
</div>
</div>
<div class="control-group" id="InAppPurchasePromotionalPriceDiv" @(Model.InAppPurchase == true ? Html.Raw("style='display: block;'") : Html.Raw("style='display: none;'"))>
<label class="control-label" for="InAppPurchasePromotionalPrice">App Friday Promotional Price for In App Purchase: </label>
<div class="controls">
@Html.TextBoxFor(o => o.InAppPurchasePromotionalPrice, new { title = "This should be at the lowest price tier of free or $.99, just for your App Friday date." })
<span class="help-inline">
@Html.ValidationMessageFor(o => o.InAppPurchasePromotionalPrice)
</span>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
此代码完美无缺,但是当我提交表单时,在服务器上请求完整帖子以显示消息.所以我创建了JavaScript代码来启用客户端验证:
requiredif.js
(function ($) {
$.validator.addMethod('requiredif', function (value, element, params) {
/*var inAppPurchase = $('#InAppPurchase').is(':checked');
if (inAppPurchase) {
return true;
}
return false;*/
var isChecked = $(param).is(':checked');
if (isChecked) {
return false;
}
return true;
}, '');
$.validator.unobtrusive.adapters.add('requiredif', ['param'], function (options) {
options.rules["requiredif"] = '#' + options.params.param;
options.messages['requiredif'] = options.message;
});
})(jQuery);
Run Code Online (Sandbox Code Playgroud)
这是我在msdn和教程中提出的方法
当然我还在表单中插入了所需的脚本:
但是......客户端验证仍然无效.那么请你帮我找一下我错过的东西?提前致谢.
Fel*_*sso 38
看看这个:http://thewayofcode.wordpress.com/tag/custom-unobtrusive-validation/
使用本教程,我的自定义验证代码运行没有问题.我能在代码中发现的唯一区别是你创建$.validator.unobtrusive.adapters.add函数的方式.参数有点不同,但问题可能只是你没有定义rule适配器的部分.
尝试使用这样的东西:
$.validator.unobtrusive.adapters.add("requiredif", ["requiredif"], function (options) {
options.rules["requiredif"] = "#" + options.params.requiredif;
options.messages["requiredif"] = options.message;
});
Run Code Online (Sandbox Code Playgroud)
或这个
$.validator.unobtrusive.adapters.add("requiredif", function (options) {
options.rules["requiredif"] = "#" + options.element.name.replace('.', '_'); // mvc html helpers
options.messages["requiredif"] = options.message;
});
Run Code Online (Sandbox Code Playgroud)
关于rule(取自链接):
jQuery规则了解这个HTML元素的数组.期望适配器将项添加到此规则数组中,以用于要附加的特定jQuery Validate验证器.该名称是jQuery Validate规则的名称,值是jQuery Validate规则的参数值.
| 归档时间: |
|
| 查看次数: |
66258 次 |
| 最近记录: |