正则表达式不匹配十进制格式

Regex not matching decimal format

我正在尝试为我的 api 控制器制作一个 post,作为参数 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; }
} 

使用此 JSON 作为请求正文

{ "Latitude": 12.345678, "Longitude": 98.765543 }

当我尝试使用 ModelState.IsValid 验证模型时,提示该模型无效。这是我在 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}$'."
]
}

我不知道我的 Regex 有什么问题。我的 Latitude/Longitude 必须在小数分隔符前至少有一位数字,并且包含 6 位小数位

ReqularExpression 注释正在验证解析的双精度值,而不是输入值。这使您的代码在验证之前调用 .ToString() 时依赖于区域设置。

我建议要么将字段更改为字符串并稍后解析它(可能在 getter 或 setter 中),要么不验证位数 - 否则你会阻止 api-传递类似“98.76554”而不是“98.765540”的用户(如果保留当前代码,即使尾随零也是一个问题)。如果需要,您还可以实施自定义验证。

如果无论如何都传递了一些不可解析的东西,它将失败。

请参阅 以获取验证此行为的代码。

为了补充 Compufreaks 的回答,我尝试在控制台应用程序中手动验证您的代码并且它工作正常,所以问题很可能在于双打的解析方式。

public class Program
{

    static void Main(string[] args)
    {
        CoordinateModel model = new CoordinateModel {Latitude = 12.345678, Longitude = 98.765543};

        var vc = new ValidationContext(model);
        var isValid = Validator.TryValidateObject(model, vc,null, true); //isValid == true

        var json = "{ \"Latitude\": 12.345678, \"Longitude\": 98.765543 }";

        model = JsonConvert.DeserializeObject<CoordinateModel>(json);
        vc = new ValidationContext(model);
        isValid = Validator.TryValidateObject(model, vc, null, true); //isValid == true
    }
}

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; }
}