2

I am trying to put in validation for the mobile number entered by the user despite putting in regular expression for 10 digit mobile number.

Here is the Model class

 public partial class student1
    {
        public int StudentId { get; set; }
        [Required]
        [StringLength(30)]
        public string Name { get; set; }
        public string Branch { get; set; }
        [Display(Name = "Mobile Number:")]
       [Required(ErrorMessage = "Mobile Number is required.")]

        [RegularExpression("^([07][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9] | 8[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9] | 9[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9])", ErrorMessage = "Invalid Mobile Number.")]
        public Nullable<int> Mobile { get; set; }
    }

Create view

   @Html.EditorFor(model => model.Mobile)
   @Html.ValidationMessageFor(model => model.Mobile, "", new { @class = "text-danger" })

When I run it, for mobile number entered less than 10 it shows the error message that I had written. But for value 10 and greater I get a new message that says

The value '999999999' is not valid for Mobile Number:.

I don't know where is this message coming from. Also, why isn't it accepting the 10 digit value?

Shad
  • 1,185
  • 1
  • 12
  • 27
  • 1
    Pranav Singh is correct about int length in C#, but explain to us how you came up with this regular expression, what do you want the expression of a mobile number to be. To help you more, try and explain each symbol you used to let us know what you were thinking. – Tasos Moustakas Dec 28 '17 at 09:22
  • You should not use an `int` (or *any* numeric type) for phone numbers if you care about preserving the leading `0`. Apart from that, phone numbers are often entered using other characters: `+`, `-`, `space`, `(`, `)`. In all applications I have worked with, it is always a string type. – Peter B Dec 28 '17 at 09:29
  • @PeterB So you mean in database I should change data type to varchar? – Shad Dec 28 '17 at 12:36
  • @TasosMoustakas in my country 10 digit mobile numbers are used beginning from 7/8/9 so there's that. – Shad Dec 28 '17 at 12:40

2 Answers2

3

Maximum value for int in c# for 64 bit machine is

2,147,483,647

which is less than 9999999999 so it is overflow for int, so it is error message for model validation from Controller before model binding.

Convert int to long

public Nullable<long> Mobile { get; set; }

Also check regular expression, it might miss some valid numbers too.

int max value for c# source:

https://msdn.microsoft.com/en-us/library/system.int32.maxvalue(v=vs.110).aspx

What is the int.MaxValue on a 64-bit PC?

Pranav Singh
  • 17,079
  • 30
  • 77
  • 104
1

try Regular Expression = ^(\d{1,3}[- ]?)?\d{10}$

Krunal Shah
  • 836
  • 8
  • 25