MVC 3 - “isDateTime”的验证不工作

发布于 2024-12-10 20:10:52 字数 764 浏览 1 评论 0原文

我有 2 个日期时间字段,我使用日期选择器供用户选择日期。但是,由于它是一个文本框,用户仍然可以输入任何值并单击提交按钮。因此,我希望对日期时间文本字段进行验证,以检查提交的值是否是具有特定格式的日期时间。我尝试了这个:

[Required(ErrorMessage = "Storage Date is required")]
[DataType(DataType.DateTime, ErrorMessage = "Please input a valid date")]
public DateTime StorageDate { get; set; }

但是,即使我在文本框中输入“xxxxx”并提交,我也没有收到任何消息(注意:[必需]验证确实有效)

我的表单是这样的:

<div class="editor-label">
    Storage Date
</div>
<div class="editor-field">
    @Html.TextBox("StorageDate", String.Format("{0:ddd, d MMM yyyy}", DateTime.Now), new { id = "storagedate" })
    @Html.ValidationMessageFor(model => model.StorageDate)
</div>

所以,我需要根据格式检查日期也..知道为什么它不起作用吗???

非常感谢任何帮助...谢谢...

I got 2 DateTime field and i use datepicker for user to choose a date. However, since it is a textbox, user can still enter any value and click the submit button. So, I wish to have validation on the DateTime textfield to check whether the value submitted is a DateTime with specific format. I tried this:

[Required(ErrorMessage = "Storage Date is required")]
[DataType(DataType.DateTime, ErrorMessage = "Please input a valid date")]
public DateTime StorageDate { get; set; }

However, I dint get any message even i input "xxxxx" in the textbox and submit (Note: the [Required] validation do work)

My form is like this:

<div class="editor-label">
    Storage Date
</div>
<div class="editor-field">
    @Html.TextBox("StorageDate", String.Format("{0:ddd, d MMM yyyy}", DateTime.Now), new { id = "storagedate" })
    @Html.ValidationMessageFor(model => model.StorageDate)
</div>

So, I need check the Date according to the format also.. Any idea why it is not working???

Any help is really appreciated...Thanks...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

云归处 2024-12-17 20:10:52

您可以将正则表达式注释添加到视图模型的属性中:

[RegularExpression("Expression_goes_here", "Date is of invalid format.")]

这是 REGEX 库的链接 - 您可以选择使用它们的表达式之一来验证日期。

You could add a regular expression annotation to the property of your view model:

[RegularExpression("Expression_goes_here", "Date is of invalid format.")]

Here is a link for a REGEX library - you may choose to use one of their expressions for validating date.

怪我太投入 2024-12-17 20:10:52

为了验证文本框中的值是否为有效日期,您需要添加带有日期格式正则表达式的 RegularExpressionAttribute。我使用自定义属性和正则表达式来验证字符串的格式是否为 mm/dd/yyyy。

public class DateAttribute : ValidationAttribute, IClientValidatable
{
    public DateAttribute()
    {
        ErrorMessage = "{0} is not a valid date";
    }

    private string _pattern = "^(((0?[1-9]|1[012])/(0?[1-9]|1\\d|2[0-8])|(0?[13456789]|1[012])/(29|30)|(0?[13578]|1[02])/31)/(19|[2-9]\\d)\\d{2}|0?2/29/((19|[2-9]\\d)(0[48]|[2468][048]|[13579][26])|(([2468][048]|[3579][26])00)))$";

    private string _fieldLabel;
    public string FieldLabel
    {
        get { return _fieldLabel; }
        set { _fieldLabel = value; }
    }

    public override string FormatErrorMessage(string name)
    {
        return String.Format(ErrorMessageString, name);
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule
        {
            ErrorMessage = FormatErrorMessage(_fieldLabel),
            ValidationType = "regex",
        };
        rule.ValidationParameters.Add("pattern", _pattern);
        yield return rule;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (String.IsNullOrEmpty(value.ToString()))
            return null;
        Regex regex = new Regex(_pattern);
        if (regex.IsMatch(value.ToString()))
            return null;

        return new ValidationResult(
            FormatErrorMessage(_fieldLabel)
        );
    }
}

用[日期]装饰属性,然后就完成了。

In order to validate that the value in the textbox is a valid date, you need to add a RegularExpressionAttribute with a regex for a date format. I use a custom attribute, with a regex to validate that a string is in the format mm/dd/yyyy.

public class DateAttribute : ValidationAttribute, IClientValidatable
{
    public DateAttribute()
    {
        ErrorMessage = "{0} is not a valid date";
    }

    private string _pattern = "^(((0?[1-9]|1[012])/(0?[1-9]|1\\d|2[0-8])|(0?[13456789]|1[012])/(29|30)|(0?[13578]|1[02])/31)/(19|[2-9]\\d)\\d{2}|0?2/29/((19|[2-9]\\d)(0[48]|[2468][048]|[13579][26])|(([2468][048]|[3579][26])00)))$";

    private string _fieldLabel;
    public string FieldLabel
    {
        get { return _fieldLabel; }
        set { _fieldLabel = value; }
    }

    public override string FormatErrorMessage(string name)
    {
        return String.Format(ErrorMessageString, name);
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule
        {
            ErrorMessage = FormatErrorMessage(_fieldLabel),
            ValidationType = "regex",
        };
        rule.ValidationParameters.Add("pattern", _pattern);
        yield return rule;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (String.IsNullOrEmpty(value.ToString()))
            return null;
        Regex regex = new Regex(_pattern);
        if (regex.IsMatch(value.ToString()))
            return null;

        return new ValidationResult(
            FormatErrorMessage(_fieldLabel)
        );
    }
}

Decorate the property with [Date], and you're set.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文