Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 正则表达式停止崩溃_C#_Regex - Fatal编程技术网

C# 正则表达式停止崩溃

C# 正则表达式停止崩溃,c#,regex,C#,Regex,考虑以下代码: [Required] [RegularExpression(@"\d{2,2}/\d{2,2}/\d{4,4} \d{2,2}:\d{2,2}:\d{2,2}", ErrorMessage = "Wrong Syntax Entered, Needed:day/Month/Year Hour:Minutes:Seconds")] public DateTime Posted { get; set; } 输入此值时,我的应用程序崩溃:00/00/0000 00:00:00 有没

考虑以下代码:

[Required]
[RegularExpression(@"\d{2,2}/\d{2,2}/\d{4,4} \d{2,2}:\d{2,2}:\d{2,2}", 
ErrorMessage = "Wrong Syntax Entered, Needed:day/Month/Year Hour:Minutes:Seconds")]
public DateTime Posted { get; set; }
输入此值时,我的应用程序崩溃:
00/00/0000 00:00:00


有没有办法阻止这种情况并使其更加现实?我想允许的日期,所以它只允许最多31天或更少的1,并允许最多12个月和最小1

正则表达式是验证日期和时间的错误方法。改用
DateTime.TryParse

编辑:

下面是一个例子:

using System;
using System.Globalization;

...

bool valid;
DateTime dt;
valid = DateTime.TryParseExact(inputString, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);

我同意@MRAB的观点,即TryParse可能更易于管理和维护

这也尝试执行您正在执行的操作,他们创建了一个自定义属性(源自
RegularExpressionAttribute
),似乎解决了他的问题。也许对你有帮助


希望这能有所帮助。

使用正则表达式验证数据时间将导致类似正则表达式的复杂问题

^([0][1-9]||[1-2][0-9]||[3][0-1])/([0][1-9]||[1][1-2])/([1][0-9]{3}) ([0][1-9]||[1][0-2]):([0][1-9]||[1-5][0-9]):([0][1-9]||[1-5][0-9])$
但我仍然怀疑它可能会遗漏一些边缘案例

如果您使用的是MVC3,那么使用自验证模型的最佳方法如下:

public class TestModel:IValidatableObject
    {
        string MyDateTime{get;set;}

        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            List<ValidationResult> v = new List<ValidationResult>();
            DateTime dt = default(DateTime);
            DateTime.TryParseExact(MyDateTime, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture,DateTimeStyles.None,out dt);
            if (dt.Equals(default(DateTime)))
                v.Add(new ValidationResult("Invalid Date time"));
            return v;
        }
    }
公共类TestModel:IValidatableObject
{
字符串MyDateTime{get;set;}
公共IEnumerable验证(ValidationContext ValidationContext)
{
列表v=新列表();
DateTime dt=默认值(DateTime);
DateTime.TryParseExact(MyDateTime,“dd/MM/yyyy HH:MM:ss”,CultureInfo.InvariantCulture,DateTimeStyles.None,out dt);
如果(dt.等于(默认值(日期时间)))
v、 添加(新的ValidationResult(“无效日期时间”));
返回v;
}
}

ModelBinder中的另一条更改格式异常消息(但将继续…)

DefaultModelBinder.GetValueInvalidResource是静态方法。我无法重写此方法。因为我创建了CustomModelBinder类并重写了SetProperty方法

[Required]
[AdditionalMetadata(
 "PropertyValueInvalid",
 "Wrong Syntax Entered, Needed:day/Month/Year Hour:Minutes:Seconds")]
public DateTime? Posted { get; set; }
并创建自定义ModelBinder

public class CustomModelBinder : DefaultModelBinder
{
    protected override void SetProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor, object value)
    {
        base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value);

        var propertyMetadata = bindingContext.PropertyMetadata[propertyDescriptor.Name];
        var invalidMessage = propertyMetadata.AdditionalValues.ContainsKey("PropertyValueInvalid")
                                 ? (string)propertyMetadata.AdditionalValues["PropertyValueInvalid"]
                                 : string.Empty;
        if (string.IsNullOrEmpty(invalidMessage))
        {
            return;
        }

        // code from DefaultModelBinder
        string fullPropertyKey = CreateSubPropertyName(bindingContext.ModelName, propertyDescriptor.Name);
        if (!bindingContext.ValueProvider.ContainsPrefix(fullPropertyKey))
        {
            return;
        }
        ModelState modelState = bindingContext.ModelState[fullPropertyKey];
        foreach (ModelError error in modelState.Errors.Where(err => String.IsNullOrEmpty(err.ErrorMessage) && err.Exception != null).ToList())
        {
            for (Exception exception = error.Exception; exception != null; exception = exception.InnerException)
            {
                if (exception is FormatException)
                {
                    string displayName = propertyMetadata.GetDisplayName();
                    string errorMessageTemplate = invalidMessage;
                    string errorMessage = String.Format(CultureInfo.CurrentCulture, errorMessageTemplate,
                                                        modelState.Value.AttemptedValue, displayName);
                    modelState.Errors.Remove(error);
                    modelState.Errors.Add(errorMessage);
                    break;
                }
            }
        }
    }
}

这个怎么样?

可能重复的不一样这是崩溃当你说“崩溃”时,你的意思是抛出一个未捕获的异常?是吗?是的,当我输入00/00/0000 00:00:00:00时,您能举个例子吗?或者我能修改我的当前表达式,使其停止00/00/00 00:00:00,并允许最多31天,最少1天,最多几个月,最少1天,最多1个月吗12@user1137472当前位置我添加了一个示例。老实说,我不知道这意味着什么,我试图实现David创建了一个类并没有成功谢谢你的努力我不知道该放在哪里,很抱歉浪费了你的时间,但我想要一个简单的答案,我想停止00/00/0000 00:00:00,只允许1到31天,1到12个月,通过明确的验证,我以前见过它,但我记不起在哪里感谢你的所有努力如果我要实现这将是一个局部类吗?我没有你知道你写了什么,人们说regx不好吗?看看那段代码,你永远无法理解它的功能。我想要的只是一个不使用服务器端验证的regx,只想要一个日期和时间表达式我理解你们的专业人士,但给我这个代码就像给一个婴儿一把枪