根据特定的字符串值验证模型 [英] Validate model on specific string values
问题描述
我正在研究Web API 2项目.除了要求某些属性的要求外,某些属性只能具有特定的值. 一种选择是,我可以尝试将模型保存到数据库(EF6)并在保存时创建一些逻辑,但是我认为最好在调用数据库之前验证是否设置了正确的值.数据注释是否提供诸如Range的属性,但是否提供特定的字符串值(如以下示例中所示)?还是我必须编写自己的验证器属性?
I'm working on a Web API 2 project. besides the requirement that some properties are required, some only can have specific values. One option is that I could try to save the model to the database (EF6) and create some logic while saving, but I think it is better to validate if the correct value is set before I make a call to the database. Does data annotations provide an attribute like Range but then for specific string values like in the example below? Or do I have to write my own validator attribute?
public class Person {
public int PersonID { get; set; }
[Required]
public string FirstName { get; set; }
public string LastName { get; set; }
[StringRange("M","F")]
public string Gender { get; set; }
}
在上面的示例中,向控制器发送信息后,唯一可以接受的值为"M"或"F".
In the above example, when a post is done to the controller, the only values to accept are "M" or "F".
推荐答案
要验证Gender属性,我通过创建一个新类(属性)创建了一个自定义验证属性:
To validate the Gender property I've created a custom validation attribute by creating a new class (attribute):
using System;
using System.Collections.Generic;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace MyProject.Models.Validation
{
public class StringRangeAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if(value.ToString() == "M" || value.ToString() == "F")
{
return ValidationResult.Success;
}
return new ValidationResult("Please enter a correct value");
}
}
}
这篇关于根据特定的字符串值验证模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!