Sam*_*Sam 12 c# validation wpf mvvm
在我的应用程序中,我有很多表单,大部分都有自己绑定的模型!当然数据验证很重要,但是没有比为所有模型实现IDataErrorInfo更好的解决方案,然后编写所有属性的代码来验证它们吗?
我已经创建了验证帮助程序,删除了很多实际的验证代码,但我仍然忍不住觉得我错过了一两招!我可以补充一点,这是我使用MVVM的第一个应用程序,所以我相信我有很多关于这个主题的知识!
编辑:
这是我真正不喜欢的典型模型的代码(让我解释一下):
string IDataErrorInfo.Error
{
get
{
return null;
}
}
string IDataErrorInfo.this[string propertyName]
{
get
{
return GetValidationError(propertyName);
}
}
#endregion
#region Validation
string GetValidationError(String propertyName)
{
string error = null;
switch (propertyName)
{
case "carer_title":
error = ValidateCarerTitle();
break;
case "carer_forenames":
error = ValidateCarerForenames();
break;
case "carer_surname":
error = ValidateCarerSurname();
break;
case "carer_mobile_phone":
error = ValidateCarerMobile();
break;
case "carer_email":
error = ValidateCarerEmail();
break;
case "partner_title":
error = ValidatePartnerTitle();
break;
case "partner_forenames":
error = ValidatePartnerForenames();
break;
case "partner_surname":
error = ValidatePartnerSurname();
break;
case "partner_mobile_phone":
error = ValidatePartnerMobile();
break;
case "partner_email":
error = ValidatePartnerEmail();
break;
}
return error;
}
private string ValidateCarerTitle()
{
if (String.IsNullOrEmpty(carer_title))
{
return "Please enter the carer's title";
}
else
{
if (!ValidationHelpers.isLettersOnly(carer_title))
return "Only letters are valid";
}
return null;
}
private string ValidateCarerForenames()
{
if (String.IsNullOrEmpty(carer_forenames))
{
return "Please enter the carer's forename(s)";
}
else
{
if (!ValidationHelpers.isLettersSpacesHyphensOnly(carer_forenames))
return "Only letters, spaces and dashes are valid";
}
return null;
}
private string ValidateCarerSurname()
{
if (String.IsNullOrEmpty(carer_surname))
{
return "Please enter the carer's surname";
}
else
{
if (!ValidationHelpers.isLettersSpacesHyphensOnly(carer_surname))
return "Only letters, spaces and dashes are valid";
}
return null;
}
private string ValidateCarerMobile()
{
if (String.IsNullOrEmpty(carer_mobile_phone))
{
return "Please enter a valid mobile number";
}
else
{
if (!ValidationHelpers.isNumericWithSpaces(carer_mobile_phone))
return "Only numbers and spaces are valid";
}
return null;
}
private string ValidateCarerEmail()
{
if (String.IsNullOrWhiteSpace(carer_email))
{
return "Please enter a valid email address";
}
else
{
if (!ValidationHelpers.isEmailAddress(carer_email))
return "The email address entered is not valid";
}
return null;
}
private string ValidatePartnerTitle()
{
if (String.IsNullOrEmpty(partner_title))
{
return "Please enter the partner's title";
}
else
{
if (!ValidationHelpers.isLettersOnly(partner_title))
return "Only letters are valid";
}
return null;
}
private string ValidatePartnerForenames()
{
if (String.IsNullOrEmpty(partner_forenames))
{
return "Please enter the partner's forename(s)";
}
else
{
if (!ValidationHelpers.isLettersSpacesHyphensOnly(partner_forenames))
return "Only letters, spaces and dashes are valid";
}
return null;
}
private string ValidatePartnerSurname()
{
if (String.IsNullOrEmpty(partner_surname))
{
return "Please enter the partner's surname";
}
else
{
if (!ValidationHelpers.isLettersSpacesHyphensOnly(partner_surname))
return "Only letters, spaces and dashes are valid";
}
return null;
}
private string ValidatePartnerMobile()
{
if (String.IsNullOrEmpty(partner_mobile_phone))
{
return "Please enter a valid mobile number";
}
else
{
if (!ValidationHelpers.isNumericWithSpaces(partner_mobile_phone))
return "Only numbers and spaces are valid";
}
return null;
}
private string ValidatePartnerEmail()
{
if (String.IsNullOrWhiteSpace(partner_email))
{
return "Please enter a valid email address";
}
else
{
if (!ValidationHelpers.isEmailAddress(partner_email))
return "The email address entered is not valid";
}
return null;
}
#endregion
Run Code Online (Sandbox Code Playgroud)
使用switch语句来识别正确的属性然后必须为每个属性编写唯一的验证函数的想法感觉太多(不是在工作方面,而是在所需的代码量方面).也许这是一个优雅的解决方案,但它只是感觉不像一个!
注意:我将根据其中一个答案中的建议将我的验证助手转换为扩展名(谢谢Sheridan)
解:
因此,按照我接受的答案,这是我最初实现它的工作的原因(显然我将改进部件 - 但我只是想让它先行,因为我没有使用lambda表达式或反射的经验在实施之前).
Validtion Dictionary类(显示主要功能):
private Dictionary<string, _propertyValidators> _validators;
private delegate string _propertyValidators(Type valueType, object propertyValue);
public ValidationDictionary()
{
_validators = new Dictionary<string, _propertyValidators>();
}
public void Add<T>(Expression<Func<string>> property, params Func<T, string>[] args)
{
// Acquire the name of the property (which will be used as the key)
string propertyName = ((MemberExpression)(property.Body)).Member.Name;
_propertyValidators propertyValidators = (valueType, propertyValue) =>
{
string error = null;
T value = (T)propertyValue;
for (int i = 0; i < args.Count() && error == null; i++)
{
error = args[i].Invoke(value);
}
return error;
};
_validators.Add(propertyName, propertyValidators);
}
public Delegate GetValidator(string Key)
{
_propertyValidators propertyValidator = null;
_validators.TryGetValue(Key, out propertyValidator);
return propertyValidator;
}
Run Code Online (Sandbox Code Playgroud)
模型实施:
public FosterCarerModel()
{
_validationDictionary = new ValidationDictionary();
_validationDictionary.Add<string>( () => carer_title, IsRequired);
}
public string IsRequired(string value)
{
string error = null;
if(!String.IsNullOrEmpty(value))
{
error = "Validation Dictionary Is Working";
}
return error;
}
Run Code Online (Sandbox Code Playgroud)
IDataErrorInfo实现(它是模型实现的一部分):
string IDataErrorInfo.this[string propertyName]
{
get
{
Delegate temp = _validationDictionary.GetValidator(propertyName);
if (temp != null)
{
string propertyValue = (string)this.GetType().GetProperty(propertyName).GetValue(this, null);
return (string)temp.DynamicInvoke(typeof(string), propertyValue);
}
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
忽略我的slapdash命名约定,并在编码的地方,我很高兴有这个工作!特别感谢nmclean当然,也感谢所有对此问题做出贡献的人,所有回复都非常有帮助,但经过一番考虑,我决定采用这种方法!
我使用extension方法来减少我必须编写的验证文本的数量.如果您不熟悉它们,请查看MSDN 上的扩展方法(C#编程指南)页面以了解extension方法.我有几十个这样可以验证每种情况.举个例子:
if (propertyName == "Title" && !Title.ValidateMaximumLength(255)) error =
propertyName.GetMaximumLengthError(255);
Run Code Online (Sandbox Code Playgroud)
在Validation.cs课堂上:
public static bool ValidateMaximumLength(this string input, int characterCount)
{
return input.IsNullOrEmpty() ? true : input.Length <= characterCount;
}
public static string GetMaximumLengthError(this string input, int characterCount,
bool isInputAdjusted)
{
if (isInputAdjusted) return input.GetMaximumLengthError(characterCount);
string error = "The {0} field requires a value with a maximum of {1} in it.";
return string.Format(error, input, characterCount.Pluralize("character"));
}
Run Code Online (Sandbox Code Playgroud)
注意,Pluralize是另一种extension,简单地增加了一个"S"的输入参数的结束时,如果输入的值不等于1的另一种方法可能是方法:
public static bool ValidateValueBetween(this int input, int minimumValue, int
maximumValue)
{
return input >= minimumValue && input <= maximumValue;
}
public static string GetValueBetweenError(this string input, int minimumValue, int
maximumValue)
{
string error = "The {0} field value must be between {1} and {2}.";
return string.Format(error, input.ToSpacedString().ToLower(), minimumValue,
maximumValue);
}
Run Code Online (Sandbox Code Playgroud)
当然,这将需要一段时间才能实现所有你需要的方法,但你会为以后节省大量的时间,你将有你的错误信息是一致的额外好处.
我个人喜欢FluentValidation方法.
这将使用基于表达式的规则替换您的切换表,例如:
RuleFor(x => x.Username)
.Length(3, 8)
.WithMessage("Must be between 3-8 characters.");
RuleFor(x => x.Password)
.Matches(@"^\w*(?=\w*\d)(?=\w*[a-z])(?=\w*[A-Z])\w*$")
.WithMessage("Must contain lower, upper and numeric chars.");
RuleFor(x => x.Email)
.EmailAddress()
.WithMessage("A valid email address is required.");
RuleFor(x => x.DateOfBirth)
.Must(BeAValidDateOfBirth)
.WithMessage("Must be within 100 years of today.");
Run Code Online (Sandbox Code Playgroud)
来自http://stevenhollidge.blogspot.co.uk/2012/04/silverlight-5-validation.html
关于这个http://fluentvalidation.codeplex.com/的更多信息- 尽管那里的文档主要是基于web-MVC的.对于Wpf,还有一些博客文章,如http://blogsprajeesh.blogspot.co.uk/2009/11/fluent-validation-wpf-implementation.html
我的看起来像这样:
new ValidationDictionary() {
{() => carer_title,
ValidationHelpers.Required(() => "Please enter the carer's title"),
ValidationHelpers.LettersOnly(() => "Only letters are valid")}
}
Run Code Online (Sandbox Code Playgroud)
ValidationDictionary 是一个 string -> delegate 的字典。它进行重载Add以接受 lambda 表达式(该表达式将转换为键的属性名称字符串)以及一params组委托,这些委托将合并为值的一个委托。委托接受一些信息,例如属性类型和值,并返回错误消息或null.
在本例中,Required和LettersOnly是高阶函数,它们生成在无效时返回给定字符串的委托。字符串本身作为委托传入,因此它们可以是动态的。
IDataErrorInfo 的实现只需在字典中查找属性名称并调用委托即可获取错误消息。
| 归档时间: |
|
| 查看次数: |
2050 次 |
| 最近记录: |