路过的ErrorMessage为客户方的验证 [英] Passing the ErrorMessage for clientside validation
问题描述
由于没有办法使用多个正则表达式模式(因为验证类型必须是唯一的)来验证一个属性(与不显眼的客户方验证)我决定延长FluentValidation这样我就可以做到以下几点。
Since there is no way to validate a property (with unobtrusive clientside validation) using multiple regex patterns (because validation type has to be unique) i decided to extend FluentValidation so i can do the following.
RuleFor(x => x.Name).NotEmpty().WithMessage("Name is required")
.Length(3, 20).WithMessage("Name must contain between 3 and 20 characters")
.Match(@"^[A-Z]").WithMessage("Name has to start with an uppercase letter")
.Match(@"^[a-zA-Z0-9_\-\.]*$").WithMessage("Name can only contain: a-z 0-9 _ - .")
.Match(@"[a-z0-9]$").WithMessage("Name has to end with a lowercase letter or digit")
.NotMatch(@"[_\-\.]{2,}").WithMessage("Name cannot contain consecutive non-alphanumeric characters");
我需要弄清楚的事情就是如何传递这是使用设置的ErrorMessage WithMessage()
通过 GetClientValidationRules()
所以它在结束了数据VAL-customregex [SOMEFANCYSTRINGHERETOMAKEITUNIQUE]属性的input元素上。
The last thing i need to figure out is how to pass the errormessage which is set using WithMessage()
via GetClientValidationRules()
so it ends up in the "data-val-customregex[SOMEFANCYSTRINGHERETOMAKEITUNIQUE]" attribute on the input element.
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) {
var rule = new ModelClientValidationRule();
rule.ErrorMessage = [INSERT ERRORMESSAGE HERE];
rule.ValidationType = "customregex" + StringFunctions.RandomLetters(6);
rule.ValidationParameters.Add("pattern", pattern);
yield return rule;
}
我一直在寻找的FluentValidation源$ C $ C,但不能弄明白。任何人有什么想法?
I've been looking at the FluentValidation sourcecode, but couldn't figure it out. Anyone got any ideas?
推荐答案
我一直在讨论如何在
与杰里米·斯金纳(流利验证的创建者)这样做
HTTP://fluentvalidation.$c$cplex.com/discussions/253505
他还跟写一个完整的例子。
He was kind enough to write a complete example.
更新
这是我们想出了在code:
Update
Here is the code we came up with:
首先扩展,为匹配和NotMatch。
First the extensions, for both Match and NotMatch.
public static class Extensions
{
public static IRuleBuilderOptions<T, string> Match<T>(this IRuleBuilder<T, string> ruleBuilder, string expression)
{
return ruleBuilder.SetValidator(new MatchValidator(expression));
}
public static IRuleBuilderOptions<T, string> NotMatch<T>(this IRuleBuilder<T, string> ruleBuilder, string expression) {
return ruleBuilder.SetValidator(new MatchValidator(expression, false));
}
}
校验器所使用的接口
The used interface for the validator
public interface IMatchValidator : IPropertyValidator
{
string Expression { get; }
bool MustMatch { get; }
}
实际验证:
The actual validator:
public class MatchValidator : PropertyValidator, IMatchValidator
{
string expression;
bool mustMatch;
public MatchValidator(string expression, bool mustMatch = true)
: base(string.Format("The value {0} match with the given expression, while it {1}.", mustMatch ? "did not" : "did", mustMatch ? "should" : "should not"))
{
this.expression = expression;
this.mustMatch = mustMatch;
}
protected override bool IsValid(PropertyValidatorContext context)
{
return context.PropertyValue == null ||
context.PropertyValue.ToString() == string.Empty ||
Regex.IsMatch(context.PropertyValue.ToString(), expression) == mustMatch;
}
public string Expression
{
get { return expression; }
}
public bool MustMatch {
get { return mustMatch; }
}
}
该适配器注册验证:
The adaptor to register the validator:
public class MatchValidatorAdaptor : FluentValidationPropertyValidator
{
public MatchValidatorAdaptor(ModelMetadata metadata, ControllerContext controllerContext, PropertyRule rule, IPropertyValidator validator)
: base(metadata, controllerContext, rule, validator)
{
}
IMatchValidator MatchValidator
{
get { return (IMatchValidator)Validator; }
}
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
{
var formatter = new MessageFormatter().AppendPropertyName(Rule.PropertyDescription);
string errorMessage = formatter.BuildMessage(Validator.ErrorMessageSource.GetString());
yield return new ModelClientValidationMatchRule(MatchValidator.Expression, MatchValidator.MustMatch, errorMessage);
}
}
最后当奇迹发生:
And finally where the magic happens:
public class ModelClientValidationMatchRule : ModelClientValidationRule
{
public ModelClientValidationMatchRule(string expression, bool mustMatch, string errorMessage)
{
if (mustMatch)
base.ValidationType = "match";
else
base.ValidationType = "notmatch";
base.ValidationType += StringFunctions.RandomLetters(6);
base.ErrorMessage = errorMessage;
base.ValidationParameters.Add("expression", expression);
}
}
更新2:
Javascript来wireup jQuery.validator:
Update 2:
Javascript to wireup jQuery.validator:
(function ($) {
function attachMatchValidator(name, mustMatch) {
$.validator.addMethod(name, function (val, element, expression) {
var rg = new RegExp(expression, "gi");
return (rg.test(val) == mustMatch);
});
$.validator.unobtrusive.adapters.addSingleVal(name, "expression");
}
$("input[type=text]").each(function () {
$.each(this.attributes, function (i, attribute) {
if (attribute.name.length == 20 && attribute.name.substring(0, 14) == "data-val-match")
attachMatchValidator(attribute.name.substring(9, 20), true);
if (attribute.name.length == 23 && attribute.name.substring(0, 17) == "data-val-notmatch")
attachMatchValidator(attribute.name.substring(9, 23), false);
});
});
} (jQuery));
这篇关于路过的ErrorMessage为客户方的验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!