MVC验证使RegularExpression仅在字符串字段上为数字 [英] MVC Validation make RegularExpression numeric only on string field

查看:231
本文介绍了MVC验证使RegularExpression仅在字符串字段上为数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的视图模型具有以下属性:

I have the following property in my view model:

[Required]
[MaxLength(12)]
[MinLength(1)]
[RegularExpression("[^0-9]", ErrorMessage = "UPRN must be numeric")]
public string Uprn { get; set; }    

不管Uprnstring,如果要在页面提交的Uprn框中输入数字以外的其他内容,我都想抛出一个验证错误.

Regardless of Uprn being a string, I want to throw a validation error if there is anything other than numbers entered into the Uprn box on page submit.

使用上面的命令,无论是字符串还是整数,我都会收到错误消息"UPRN必须为数字"

With the above, I am getting the error "UPRN must be numeric" whether its a string or int

这是怎么回事?

推荐答案

正则表达式错误.替换为:

The regular expression is wrong. Replace it with:

[Required]
[MaxLength(12)]
[MinLength(1)]
[RegularExpression("^[0-9]*$", ErrorMessage = "UPRN must be numeric")]
public string Uprn { get; set; }    

别忘了包括:

@Scripts.Render("~/bundles/jqueryval")

您认为要进行jquery验证

in your view for the jquery validation

这篇关于MVC验证使RegularExpression仅在字符串字段上为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆