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
Validating a credit card number is probably something that you don’t want to implement client validation for.
But in case you are interested how to achieve it in the general case you will have to implement the same logic you have on your server in javascript.
There’s just one thing that is wrong with your custom validation attribute and this is name of the validation type which must contain only lowercase letters:
Once we have fixed that we could implement the same validation logic on the client:
Obviously all the script stuff goes into a separate file and not inside the view. I just left it here for easier readability.