用于验证数据类型的 MVC 数据注释
如何针对这种场景定制数据注释验证。
我收到此错误:
值“选择省份”不是 对省份有效。
我想要这样的
请选择一个国家
我的 ViewModel 如下所示:
[DisplayName("Province")]
[UIHint("ProvinceDropDown")]
public long? ProvinceId { get; set; }
我的视图是一个选择列表:
<select name="ProvinceId" id="ProvinceId" class="input-validation-error">
<option value="">Select Province</option>
<option value="613">Allen </option>
<option value="614">Anderson</option>
// data truncated ....
</select>
How do you customize data annotation validation for this scenario.
I am receiving this error:
The value 'Select Province' is not
valid for Province.
I want it like this
Please select a country
My ViewModel looks like this:
[DisplayName("Province")]
[UIHint("ProvinceDropDown")]
public long? ProvinceId { get; set; }
My View is a select list :
<select name="ProvinceId" id="ProvinceId" class="input-validation-error">
<option value="">Select Province</option>
<option value="613">Allen </option>
<option value="614">Anderson</option>
// data truncated ....
</select>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要将
ErrorMessage = "Please Select a Country"
添加到注释属性,类似于 示例如下:You need to add
ErrorMessage = "Please Select a Country"
to your annotation attribute, similar to the example here:要自定义验证器,您可以从 ValidationAttribute 继承:
我认为您不需要这样做,但应该尝试使您的可为空长字符串,并在此属性上使用验证器。
然后将您的视图模型转换为某个域模型,一旦验证通过,该域模型就可以为空。
To customize the validators you can inherit from ValidationAttribute:
I think you won't need to do this but instead should try making your nullable long a string, and having the validators on this property.
Then converting your View Model to some domain model which has the nullable long once the validation has passed.