I am trying to make a post to my api controller, passing as parameter CoordinateModel class
public class CoordinateModel
{
[Range(-90, 90)]
[RegularExpression(@"^\d+\.\d{6}$")]
public double Latitude { get; set; }
[Range(-180, 180)]
[RegularExpression(@"^\d+\.\d{6}$")]
public double Longitude { get; set; }
}
Using this JSON as request body
{ "Latitude": 12.345678, "Longitude": 98.765543 }
When I try to validate the model with ModelState.IsValid
is saying the model is not valid. This is the resposne I get on Postman
{
"Latitude": [
"The field Latitude must match the regular expression '^\\d+\\.\\d{6}$'."
],
"Longitude": [
"The field Longitude must match the regular expression '^\\d+\\.\\d{6}$'."
]
}
I can't figure out what's wrong with my Regex. My Latitude/Longitude must have at least one digit before the decimal separator and contain 6 decimals digits
The ReqularExpression-annotation is validating the parsed double value, not the input value. This makes your code dependent on the region settings as it calls .ToString() before validating it.
I'd recommend either changing the field to string and parsing it later on (maybe in a getter or setter) or not validating the number of digits - otherwise you will block api-users that pass something like "98.76554" instead of "98.765540" (what is an issue even with the trailing zero if you keep your current code). You also might implement a custom validation if you need to.
It will fail if something not-parseable is passed anyways.
See the post from SBFrancies for code to proof this behavior.