我对依赖于其他 3 个字段的字段进行复杂验证服务器上的验证很简单,因为我使用“验证”的方法
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
// my validation
if(complex_condition)
{
yield return new
ValidationResult("my error", new List<string> {"field1"});
}
}
但不知道如何在客户端上做同样的事情。可以将验证放在“提交”事件中,但我希望在我正在验证的字段中显示错误消息,就像触发了所需的字段验证一样。
谢谢你。
编辑:回复@DarinDimitrov 后的解决方案:
Javascript:
$.validator.addMethod('mycustomvalidation', function (value, element, parameters) {
if (value.length < 6) {
return false;
}
return true;
});
$.validator.unobtrusive.adapters.add('mycustomvalidation', [], function (options) {
options.rules['mycustomvalidation'] = {};
for(var key in options.params) {
options.rules['mycustomvalidation'][key] = options.params[key];
}
options.messages['mycustomvalidation'] = options.message;
});
我可以创建一个自定义数据注释:
模型:
[CustomClientValidation("mycustomvalidation", "value1", "value2", ErrorMessage="validacion propia")]
public string MyProperty { get; set; }
数据注释:
public class CustomClientValidationAttribute : ValidationAttribute, IClientValidatable
{
public CustomClientValidationAttribute(string validationType)
{
this.ValidationType = validationType;
}
public CustomClientValidationAttribute(string validationType, params object[] parameters)
: this(validationType)
{
if (parameters != null && parameters.Count() > 0)
{
this.ValidationParameters = new Dictionary<string, object>();
var countParameters = parameters.Count();
for (var index = 0; index < countParameters; index++)
{
this.ValidationParameters.Add(string.Format("parameter{0}", index), parameters[index]);
}
}
}
public string ValidationType { get; set; }
public IDictionary<string, object> ValidationParameters { get; set; }
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule()
{
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
ValidationType = this.ValidationType,
};
if (this.ValidationParameters != null)
{
foreach (var parameter in this.ValidationParameters)
{
rule.ValidationParameters.Add(parameter.Key, parameter.Value);
}
}
yield return rule;
}
public override bool IsValid(object value)
{
return true;
}
}
或使用 javascript:
$.validator.addMethod('mycustomvalidationii', function(value) {
if (value.length < 6) {
return false;
}
return true;
}, 'my custom validation');
$("#MyProperty").rules("add", "mycustomvalidationii");