Mukesh Reddy
Mukesh Reddy

Reputation: 21

How To Restrict Integer To Allow Up To 10 Digits

I want to restrict an integer to allow maximum 10 digits .i.e from 0 to any number(XXXXXXXXXX)

I am using C# and .NET Web API

In my Class(.cs) file i have used like this

[RegularExpression(@"^\d{1,10}$", ErrorMessage = "Invalid RequestedN")] 
[Display(Name = "RequestedN")]
public int RequestedN { get; set; }

I will get a JSON response on clicking my submit button..I will validate that JSON(object) by validating ModelState in Controller...

When I enter 11 digits it is showing message as below

"JSON integer 91234567890 is too large or small for an Int32. Path 'Quotas[0].RequestedN', line 1, position 81."

But I want message as "Invalid RequestedN"

I have tried another RegularExpression as below but no use.

^([1-9]|([1-9][0-9])|([1-9][0-9][0-9])|([1-9][0-9][0-9][0-9])|([1-9][0-9][0-9][0-9][0-9])|\d{6}|\d{7}|\d{8}|\d{9}|\d{10})$

Suggest any idea or solution to this problem

Upvotes: 1

Views: 2932

Answers (2)

Mulders Michiel
Mulders Michiel

Reputation: 98

You will have to use Int64:

Int64 is an immutable value type that represents signed integers with values that range from negative 9,223,372,036,854,775,808 (which is represented by the Int64::MinValue constant) through positive 9,223,372,036,854,775,807 (which is represented by the Int64::MaxValue constant. The .NET Framework also includes an unsigned 64-bit integer value type, UInt64, which represents values that range from 0 to 18,446,744,073,709,551,615.

So convert your number to Int64 and then you can use your expression: ^\d{1,10}$

Upvotes: 3

Anonymous Duck
Anonymous Duck

Reputation: 2978

Because the value you entered is greater than the value an Int32 can hold.

See link : Int32

The value of this constant is 2,147,483,647; that is, hexadecimal 0x7FFFFFFF.

If you want to support ten digits, please consider another datatype.

Maybe Int64 which is the long data type.

Upvotes: 2

Related Questions