2

I have a problem similar to this question

I'm using MVC. I have added a regular expression in my ViewModel to force the users to enter a number with 1 or 2 decimal places. I am thinking there must be an error in my Regex but the same statement is working fine elsewhere.

If I put in 0.00 as my rate, when I submit my form, ModelState.IsValid returns as false.

[RegularExpression(@"^(\d+\.\d{1,2})$", ErrorMessage = "Please enter valid rate with 1 or 2 decimal places")]
public double DecimalRate { get; set; }
  • If I type any invalid input, it behaves as expected, displaying the proper error message and not letting me save the page
  • If I put valid input (other than 0.00), it saves properly.
  • If I remove the Regex completely, 0.00 is seen as valid input and it saves properly.

As per a suggestion in this question, I have verified that this rate is causing the error by setting a debug at ModelState.IsValid in Visual Studio and checking the errors.

I have a hunch it might have something to do with the attribute being of type double?

Community
  • 1
  • 1
Ona_17
  • 35
  • 1
  • 8
  • Oh, sorry I didn't realize Rate might be a special keyword. In my code the name is different, I just changed it here for simplicity. I'll edit my post – Ona_17 Jun 20 '16 at 16:57

1 Answers1

1

This is happening because your property's data type is double (not string), so it doesn't represent a series of characters. It represents a numerical value. If your input is 0.00, then it will represent the value 0, and not match the regex. I suspect you will encounter the same issue for numbers like 3.00 as well.

If you need the user's inputs to be in a specific format, change your field to a string and then use Convert.ToDouble() when and if you need to convert it to a number.

JLRishe
  • 99,490
  • 19
  • 131
  • 169
  • Ah yes you are correct about the 3.00 having the same behaviour. I find it odd that 0.00 was able to save properly as a double when the regex was not present, but that when it gets converted from a string to a double for the regex, the .00 is dropped. – Ona_17 Jun 20 '16 at 15:46
  • There is nothing odd about being able to save `0.00` as a `double`. It is simply converted to the value `0`, which is a valid `double`. If that is converted back to a string again in order to apply a regex to it, it will not match the regex `^(\d+\.\d{1,2})$` because its string value wouldn't have a decimal portion. – JLRishe Jun 20 '16 at 15:50