.net 透過特性及繼承IValidatableObject完成自定義表單驗證

潇潇mini發表於2024-04-17
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);
}

最後丟擲結果如下圖:

圈出來的就是你自定義丟擲的內容了

相關文章