英文:
Checking Property value: Data validation using Data Annotations - .NET
问题
我想要验证属性值是否设置为特定文本。我查阅了[验证文档](https://www.tutorialsteacher.com/mvc/implement-validation-in-asp.net-mvc)并了解到有许多选项,如必填项,非常有帮助。但我没有找到确保属性具有特定值的选项。是否可以使用数据注释来实现?是否可以使用正则表达式?
即:
ClassName属性必须设置为“science”。是否有用于属性值的数据注释?是否有正则表达式?
英文:
I am wanting to validate that a property value is set to a specific text. I came across [validation] (https://www.tutorialsteacher.com/mvc/implement-validation-in-asp.net-mvc) and saw how there are many options such as Required which is very helpful. But I do not see one to ensure that a property has a specific value. Is there a way I can do that using data annotations? Is regular expression for that?
i.e.
ClassName property must be set to "science". Is there a data annotation for property values? Is regular expression for that?
public class Student{
[DataAnnotation("science")]
public string ClassName{ get; set; }
}
I have searched over a few articles and still cannot find the solution to my problem. Would like to know if this is possible with data annotations?
答案1
得分: 0
请使用CustomValidationAttribute。请参考以下链接:
https://learn.microsoft.com/en-us/previous-versions/aspnet/cc668224(v=vs.100)
https://www.codeproject.com/Tips/5257153/How-to-Create-Custom-Validation-Attribute-in-Cshar
基本上,这些属性将具有IsValid函数。在您的情况下,您可以将验证设置为属性值== science。
英文:
You need to Use CustomValidationAttribute. Please refer below
https://learn.microsoft.com/en-us/previous-versions/aspnet/cc668224(v=vs.100)
https://www.codeproject.com/Tips/5257153/How-to-Create-Custom-Validation-Attribute-in-Cshar
Basically, these attributes will have Isvalid function. In you case you can put the validation as Property value == science
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论