MVal Modal Validation ErrorMessage for Decimal Datatype with Globalization

I think this topic explains a lot. But I'll try to explain a little more ...

First of all, I want to mention that I installed the globalize js library with nuget. So, in the decimal field, people can add numbers with "." ... and "," depending on their browser locale settings. This was the first catch I was able to solve.

The second problem is displaying error messages according to the locale setting. I used resource files to make this happen and it worked fine until I realized that some posts are not using strings in resource files. For example, when I write a letter instead of a number (I'm talking about this decimal field), the error message is

The field Price must be a number. 

      

I couldn't figure out how to change this until I see some questions similar to mine. Some have solved this problem with regular expressions. I could have done that, but you see, I set up globalization for everything else, and now I have to decide if the user will put "," or "." ... in a decimal field. I just don't want to go this way.

Here is the code I used to create this field in the modal class

[Required(ErrorMessageResourceType = typeof(Resources.Validation), ErrorMessageResourceName = "Required")]
[Display(Name = "Fiyat")]
[DataType(DataType.Currency, ErrorMessage = "Fiyat geçerli değil.")] // I know that
doesn't work, but couldn't really figure out why there is an error message for datatype at all.
[Range(0, 100, ErrorMessageResourceType = typeof(Resources.Validation), ErrorMessageResourceName = "Range")]
public decimal Price { get; set; }

      

Could you please give me some ideas on how to show the correct message (correct language using resource files) when the user enters letters or just uses "," or "." ... when their locale doesn't allow them?

+3


source to share


1 answer


As I said in my comment, I ran into the same problem and I ended up doing the following:

Use a regex just to know if it's a valid number (accepts both a comma / period as the decimal separator for multiple cultures), and leave the range data to test if the number is valid (use a comma / period ) and the range itself. Seems to work pretty well :)



[Display(Name = "TdPrime", ResourceType = typeof(Resources.Somethings.Something))]       
[RegularExpression(@"-?(?:\d*[\,\.])?\d+", 
                ErrorMessageResourceName = "DataType_Number", 
                ErrorMessageResourceType = typeof(Validations))]       
[Range(0, 999.9999, 
          ErrorMessageResourceName = "RangeAttribute_ValidationError",
          ErrorMessageResourceType = typeof(Validations))]
[DisplayFormat(DataFormatString = "{0:#.####}", ApplyFormatInEditMode = true)]
public decimal? TdPrime { get; set; }

      

It seems like you've decided to use angular, but at least next time you will have another solution to choose from :)

+1


source







All Articles