[英]Data annotation validation for an invalid string
The scenario is this: 场景是这样的:
I have a list of countries in a dropdown box and have a select attribute called "Not Found" I had to include this as this was a text field so there is a lot of rubbish! 我在下拉框中有一个国家列表,并且有一个名为“未找到”的选择属性,我必须包括它,因为这是一个文本字段,所以有很多垃圾!
So when a user creates a from lets say, if they choose the "Not Found" option, I want an error to say "select valid country" pretty easy... 因此,当用户创建一个From时,如果他们选择“ Not Found”(未找到)选项,那么我会想说一个错误,即“选择有效的国家/地区”非常容易...
But I am having trouble finding the correct annotation 但我找不到正确的注释
[???(ErrorMessage = "Select a valid country.")]
public string Country
{
get
set
}
But what attribute do I need to put when the ?s are? 但是,当?s是时,我需要设置什么属性?
Thanks 谢谢
I think you want to create a custom attribute. 我认为您想创建一个自定义属性。 Something like this:
像这样:
class YourValidationAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
// Do your validation check....and return a ValidationResult
return ValidationResult.Success;
}
}
Then annotate your class with it: 然后用它注释您的班级:
[YourValidationAttribute]
public string Country
{
get
set
}
See this too: https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.validationattribute%28v=vs.110%29.aspx 也请参见以下内容: https : //msdn.microsoft.com/zh-cn/library/system.componentmodel.dataannotations.validationattribute%28v=vs.110%29.aspx
I would use the predefined CustomValidation Annotation. 我将使用预定义的CustomValidation注释。
https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.customvalidationattribute(v=vs.95).aspx https://msdn.microsoft.com/zh-CN/library/system.componentmodel.dataannotations.customvalidationattribute(v=vs.95).aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.