.net 通过特性及继承IValidatableObject完成自定义表单验证

Model:
public class PartAItem : IValidatableObject
{
    [Required]
    public string TOKEN { get; set; }
    [Required]
    public string PROJECT_ID { get; set; }
    public string PART { get; set; }
    [Required]
    public string FORM_ID { get; set; }
    public string RATING{ get; set; }
    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        //yield return ValidationUtil.Validate_Mandatory(this, "CodeTableModel.Value");

      var ratings = new List<string>() { "C", "A", "N", "G", "S", "P" };

        if (!ratings.Contains(RATING))
        {
            yield return new ValidationResult("PART_A.ITEMS.RATING  must be either " + string.Join(",", ratings) + " or null");
        }
        yield return null;
    }
}

在控制器中可以通过ModelState.IsValid 判断表单验证是否通过

if (!ModelState.IsValid)
    return Content(JsonResultFactory.CreateAPIFailResultPSB(errorCode, "Parameter error" + GetValidationErrors(ModelState)), contentType);

可以自定义方法来向外抛出验证后的错误内容

private string GetValidationErrors(ModelStateDictionary modelState)
{
    var query = from state in modelState.Values
                from error in state.Errors
                select error.ErrorMessage;

    var errorList = query.ToList();
    return string.Join(",", errorList);
}

最后抛出结果如下图:

 圈出来的就是你自定义抛出的内容了

posted @ 2024-04-17 17:10  潇潇mini  阅读(11)  评论(0编辑  收藏  举报