Reputation: 1844
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.
Upvotes: 0
Views: 165
Reputation: 82096
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.
NaN
Here's a revised version of your validator
jQuery.validator.addMethod('validDate', function (value, element, params) {
return !isNaN(Date.parse(value));
}, '');
Upvotes: 1
Reputation: 11
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 a t in the function.
Upvotes: 1