Created a custom validation attribute and I would like to get it to work on client side as well. Here is the Model class
public class CreditCardAttribute : ValidationAttribute, IClientValidatable
{
public override bool IsValid(object value)
{
var number = Convert.ToString(value);
return IsValidNumber(number);
}
private bool IsValidNumber(string number)
{
int[] DELTAS = new int[] { 0, 1, 2, 3, 4, -4, -3, -2, -1, 0 };
int checksum = 0;
char[] chars = number.ToCharArray();
for (int i = chars.Length - 1; i > -1; i--)
{
int j = ((int)chars[i]) - 48;
checksum += j;
if (((i - chars.Length) % 2) == 0)
checksum += DELTAS[j];
}
return ((checksum % 10) == 0);
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
yield return new ModelClientValidationRule {
ErrorMessage = this.ErrorMessage,
ValidationType = "CreditCard"
};
}
}
jQuery:
jQuery.validator.addMethod('CreditCardtest', function (value, element, params)
{
return false;
});
jQuery.validator.unobtrusive.adapters.add('CreditCard', { }, function(options){
options.rules['CreditCardtest'] = true;
options.messages['CreditCardtest'] = options.message;
});
I am not sure what should go to CreditCardTest, do I want to rewrite what I have in Model to here?
Thank you
IClientValidatableto the model and I completely removed the jquery code and it works. I thought it needs the jQuery part to work?