MVC Validation make RegularExpression numeric only on string field

前端 未结 4 1195
轻奢々
轻奢々 2021-01-01 10:40

I have the following property in my view model:

[Required]
[MaxLength(12)]
[MinLength(1)]
[RegularExpression(\"[^0-9]\", ErrorMessage = \"UPRN must be numeri         


        
相关标签:
4条回答
  • 2021-01-01 10:50

    Or you could do the length validation in the regexp:

    [Required]
    [RegularExpression("^[0-9]{1,12}$", ErrorMessage = "...")]
    public string Uprn { get; set; }
    

    Here's the regex visualized:

    Regular expression visualization

    Debuggex Demo

    0 讨论(0)
  • 2021-01-01 10:51

    I suggest you use either:

    [RegularExpression("\d*", ErrorMessage = "UPRN must be numeric")]
    

    *note that it will accept empty if you remove [Required] and [MinLength(1)]

    or use the following:

    [RegularExpression("\d+", ErrorMessage = "UPRN must be numeric")]
    

    which will only accept one more digits

    you can test your regular expressions here: https://regex101.com/

    0 讨论(0)
  • 2021-01-01 10:52

    The RegEx should be ^[0-9]*$.

    I.E.

    The property should look like:

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

    See working example.


    I'm sure you already have jQuery referenced but make sure jQuery validate and Microsoft validate scripts are included.

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    
    <script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
    
    <script src="//ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js"></script>
    
    0 讨论(0)
  • 2021-01-01 11:01

    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; }    
    

    Don't forget to include:

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

    in your view for the jquery validation

    0 讨论(0)
提交回复
热议问题