How to make RequiredAttribute work with an enum field

后端 未结 2 1127
星月不相逢
星月不相逢 2021-01-19 09:58

I\'ve recently realized that RequiredAttribute does not work on enum fields. Let\'s say I have two select elements called ddlOfficers and ddlApplicationTypes on the form bot

2条回答
  •  有刺的猬
    2021-01-19 10:34

    There's nothing wrong with your custom helper. The HTML clearly shows that the required data validation has been added (data-val-required). Simply, the issue is that that your enum always has an acceptable value. You may not consider None acceptable, but from the enum's perspective, it's just fine. So you have two choices:

    1. Add your own custom validation to ensure that None is not selected. You'll need to handle this both client and server-side, because you're completely on your own here.

    2. If you can change the enum, you can remove the None option, and then simply use a nullable enum on your model/view model property, i.e.:

      public AppType? ApplicationType { get; set; }
      

      Then, the required validation will work as expected.

提交回复
热议问题