c# - 正则表达式模型验证 : Whole Number or Decimal Multiples of . 25

标签 c# regex entity-framework attributes data-annotations

我正在尝试编写一个正则表达式来匹配表示为 .25 的十进制倍数的数值(例如 1.2514.75).

// Must Match
1.0
1.25
1.250000
1.5
1.500
1.75
1.7500

// Must Not Match
1.2
1.46
1.501
1.99

到目前为止,我有以下表达式:\d+(\.((0+)|(250*)|(50*)|(750*)))。当我使用像 gskinner.com/regexr 这样的在线工具时它会起作用。 。当我在验证属性中使用表达式来为 EntityFramework 数据库提供种子时,它会产生验证错误:

[RegularExpression(@"^\d+(\.((0+)|(250*)|(50*)|(750*)))$", ErrorMessage = "Hours must be 15 minute increments expressed as decimals (ex. .0, .25, .5, .75)")]
public double Hours { get; set; }

类似的问题( I am looking for a way to round the decimal portion of numbers up or down to the nearest .25, .5, .75, or whole number ),但我需要使用正则表达式来使用上述数据注释。

问题:

  1. 有人看出我的表情有什么问题吗?

  2. 如果您可以扩展它以支持整数(例如 44.25 但不是 4。4.62)

最佳答案

匹配此类数字,请使用正则表达式模式

 (?!0\d)\d+(?:[.](?:25|5|75|0)0*)?(?!\d)

验证输入是这样的数字,请使用正则表达式模式

 ^(?!0\d)\d+(?:[.](?:25|5|75|0)0*)?$

在这两种情况下,第一部分 (?!0\d) 是可选的,以禁止匹配/验证具有无效前导零的数字,例如 000003.250,当match 会修剪它们并只需要 3.250;如果正则表达式中存在此可选部分,验证将失败。

关于c# - 正则表达式模型验证 : Whole Number or Decimal Multiples of . 25,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13390037/

相关文章:

c# - 使用 Entity Framework 插入时有条件地设置 Identity 字段

c# - 大批量 Entity Framework 更新比我自己批处理慢得多

c# - 快速创建和删除文件导致异常

c# - 打开带有预先确定的 cookie 集的网页

c# - 带有 View 的 Entity Framework 6 迁移

用于替换部分字符串(包括单引号 ('))的正则表达式

Java:替换所有 ' in a string with\'

javascript - 用于查找不匹配的 mustache 表示法的正则表达式会在正确出现的情况下找到完全匹配

database - EntityFramework 启用迁移 ArgumentException

c# - 使用 C# 在特定设备中播放声音