简体   繁体   English

如何在日期字符串模型属性上获得客户端验证

[英]How to get client side validation on a date string model property

In my model I have an object that contains a date property. 在我的模型中,我有一个包含date属性的对象。 (String is used because that is what the previous programmer wrote): (使用字符串,因为这是以前的程序员写的):

[Display(Name = "Payment Date")]
[Date(ErrorMessage = "Please enter a valid date")]
public string PaymentDate { get; set; }

Here is the custom date attribute used by PaymentDate : 这是PaymentDate使用的自定义日期属性:

public sealed class DateAttribute : ValidationAttribute, IClientValidatable 
{
    public override bool IsValid(object value)
    {
        var dateString = value as string;
        if (string.IsNullOrWhiteSpace(dateString))
        {
            return false;
        }
        DateTime result;
        var success = DateTime.TryParse(dateString, out result);
        return success;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        return new ModelClientValidationRule[] { new ModelClientValidationRule 
        { 
            ValidationType = "paymentdate", 
            ErrorMessage = this.ErrorMessage } 
        };
    }
}

This works great on the server side, but not on the client side. 这在服务器端效果很好,但在客户端效果不佳。 Here in the view I tried to create a custom function to do the validation, but it does not seem to work properly. 在此视图中,我尝试创建一个自定义函数来进行验证,但是它似乎无法正常工作。 There is a syntax error caused by the dot before test test前的句点引起语法错误

    // custom jquery validation method    
    jQuery.validator.addMethod('validDate', function (value, element, params) {
        return Invalid|NaN/.test(new Date(value)); 
    }, '');

    // unobtrusive adapter
    jQuery.validator.unobtrusive.adapters.add('paymentdate', {}, function (options) {
        options.rules['validDate'] = true;
        options.messages['validDate'] = options.message;
    });

How can I get client-side validation working with my already-working server side validiation? 如何使客户端验证与已经工作的服务器端验证一起工作?

Note: I'm using a custom attribute because some custom validation will be added later. 注意:我使用的是自定义属性,因为稍后会添加一些自定义验证。

jQuery.validator.addMehod('validDate', function (value, element, params) {
        return Invalid|NaN/.test(new Date(value)); 
    }, '');

with

jQuery.validator.addMethod('validDate', function (value, element, params) {
        return Invalid|NaN/.test(new Date(value)); 
    }, '');

Looks like you're missing at in the function. 好像您在该函数中不见了。

The syntax error is thrown because the regex is not valid, you need a / at the beginning 由于正则表达式无效,因此引发语法错误,您需要在开头添加/

/Invalid|NaN/.test(...)

However, couple of things I would point out. 但是,我要指出几件事。

  1. It's recommended you use Date.parse when parsing date strings 建议您在解析日期字符串时使用Date.parse
  2. It's better to use the isNaN function when checking for NaN 检查NaN时最好使用isNaN函数

Here's a revised version of your validator 这是验证器的修订版

jQuery.validator.addMethod('validDate', function (value, element, params) {
    return !isNaN(Date.parse(value)); 
}, '');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM