title: How to get client side validation on a date string model property
body: <p>In my model I have an object that contains a date property. (String is used because that is what the previous programmer wrote):</p>
  
  <pre><code>[Display(Name = "Payment Date")]
  [Date(ErrorMessage = "Please enter a valid date")]
  public string PaymentDate { get; set; }
  </code></pre>
  
  <p>Here is the custom date attribute used by <code>PaymentDate</code>:</p>
  
  <pre><code>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&lt;ModelClientValidationRule&gt; GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
      {
          return new ModelClientValidationRule[] { new ModelClientValidationRule 
          { 
              ValidationType = "paymentdate", 
              ErrorMessage = this.ErrorMessage } 
          };
      }
  }
  </code></pre>
  
  <p>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 <code>test</code></p>
  
  <pre><code>    // 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;
      });
  </code></pre>
  
  <p>How can I get client-side validation working with my already-working server side validiation?</p>
  
  <p>Note: I'm using a custom attribute because some custom validation will be added later.</p>