Dataannotation仅验证数值 [英] Dataannotation validate for numeric values only

查看:72
本文介绍了Dataannotation仅验证数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的asp.net应用程序中使用DAValidation,我必须对联系号码应用数字验证,也要在联系号码上应用最小11位数字。

这就是我的方式正在应用注释



I am using DAValidation in my asp.net application, I have to apply Numeric validation on contact number, also on the length on contact number which should be minimum 11 digits.
This is how I am applying annotation

[StringLength(20, MinimumLength = 11, ErrorMessage = "Contact number should have minimum 11 digits")]
        [Range(0, Int64.MaxValue, ErrorMessage = "Contact number should not contain characters")]
        public string CONTACT_NUMBER
        {
            get { return m_CONTACT_NUMBER; }
            set
            {
                m_CONTACT_NUMBER=value;
            }
        }





工作正常,但我遇到的问题是如果我输入abc在联系号码字段中,它将首先检查长度(即它给出错误消息(联系号码应至少有11位)),但是它应该验证非数字输入的数据类型。

如何解决这个问题?



我尝试过:





It is working fine,but the problem I am facing is that if I enter abc in contact number field,it will check for length first(ie it gives error message (Contact number should have minimum 11 digits)), However it should validate the datatype incase of non numeric input.
How can I fix this?

What I have tried:

[StringLength(20, MinimumLength = 11, ErrorMessage = "Contact number should have minimum 11 digits")]
        [Range(0, Int64.MaxValue, ErrorMessage = "Contact number should not contain characters")],/pre>

推荐答案

添加如下代码



Add code as below

[DataType(DataType.PhoneNumber)]
    [Display(Name = "CONTACT_NUMBER ")]
    [Required(ErrorMessage = "CONTACT_NUMBER Required!")]
    [RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})


,ErrorMessage = 输入的CONTACT_NUMBER格式无效。)]
public string CONTACT_NUMBER { get ; set ;}
", ErrorMessage = "Entered CONTACT_NUMBER format is not valid.")] public string CONTACT_NUMBER { get; set; }


范围属性放在顶部

Place the Range Attribute at top
[Range(0, Int64.MaxValue, ErrorMessage = "Contact number should not contain characters")]
       [StringLength(20, MinimumLength = 11, ErrorMessage = "Contact number should have minimum 11 digits")]
       public string CONTACT_NUMBER
       {


这篇关于Dataannotation仅验证数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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