1

I am new to MVC. I am trying to validate text box value for only integers.

Here is my property and data annotations that I have tried so far

    [Required(ErrorMessage = @"Must Enter EOT Months")]
    [RegularExpression("([0-9]+)", ErrorMessage = @"EOT Months ")]
    [Range(0, int.MaxValue, ErrorMessage = @"EOT Months must be numeric and a whole number")]
    public int PayoutEOTMths
    {
        get { return DisposalConstant.PayoutEOTMths; }
        set { DisposalConstant.PayoutEOTMths = value; }
    }

But whenever I am entering value such as 6.5. It is giving me default validation message that is

•The value '6.5' is not valid for PayoutEOTMths.
Divyang Desai
  • 7,483
  • 13
  • 50
  • 76
Adeel
  • 413
  • 1
  • 7
  • 22
  • Because 6.5 is decimal ??? So that is the expected behavior rite ? You may consider some client side plugins which will not let the user enter `.` – Shyju Sep 28 '16 at 02:15
  • I know that. I just want my custom error message in such situations. – Adeel Sep 28 '16 at 02:21
  • Are you sure that message is not from client side validation? Your custom messages are used only if the request hits the server, and Model.IsValid fails. However, some annotation include client side validation automatically and you can't change the message so easily. – victor Sep 28 '16 at 02:30
  • type int doesn't allow for decimal places, try using a double or float – nocturns2 Sep 28 '16 at 02:33
  • It give the default message because its not an `int`. What error message were you expecting (and your `RegularExpressionAttribute` is pointless). –  Sep 28 '16 at 02:52
  • Stephen, Can I catch it using data annotation that user entered float instead of integer ? – Adeel Sep 28 '16 at 03:12
  • @Adeel your input and model validation does not match, you entered a decimal value of `6.5` but in your validation states that I want to accept only integers `[RegularExpression("([0-9]+)", ErrorMessage = @"EOT Months ")]` – Anonymous Duck Sep 28 '16 at 03:14
  • I just gave 6.5 as an example. I want my data annotation to catch those mistakes. I hope it make some sense. – Adeel Sep 28 '16 at 03:17
  • 1
    If your wanting to change the default error message for an invalid property, then refer [this answer](http://stackoverflow.com/questions/6214066/how-to-change-default-validation-error-message-in-asp-net-mvc) –  Sep 28 '16 at 04:42

0 Answers0