简体   繁体   中英

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

In my model I have an object that contains a date property. (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 :

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

    // 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
  2. It's better to use the isNaN function when checking for NaN

Here's a revised version of your validator

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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