Validate model on specific string values

后端 未结 3 663

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 m

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-07 04:38

    you can use reqular expression like this:

    [RegularExpression("M|F", ErrorMessage = "The Gender must be either 'M' or 'F' only.")]
    public string Gender { get; set; }
    

    but in my api it will show error message when i passed data so you can add

    [StringLength(1, MinimumLength = 1, ErrorMessage = "The Gender must be 1 characters.")]
    

    final code:

    [StringLength(1, MinimumLength = 1, ErrorMessage = "The Gender must be 1 characters.")]
    [RegularExpression("M|F", ErrorMessage = "The Gender must be either 'M' or 'F' only.")]
    public string Gender { get; set; }
    

提交回复
热议问题