检查属性值:使用数据注释进行数据验证 – .NET

huangapple go评论66阅读模式
英文:

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

https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations.customvalidationattribute?view=netframework-4.8

基本上,这些属性将具有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

https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations.customvalidationattribute?view=netframework-4.8

Basically, these attributes will have Isvalid function. In you case you can put the validation as Property value == science

huangapple
  • 本文由 发表于 2023年2月14日 01:58:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/75439590.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定