Checking a credit card number is probably something you donβt want to implement to verify a customer.
But if you are wondering how to achieve this in the general case, you will have to implement the same logic as on your server in javascript.
Only one thing that doesn't match your custom validation attribute is the name of the validation type, which should only contain lowercase letters:
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { yield return new ModelClientValidationRule { ErrorMessage = this.ErrorMessage, ValidationType = "creditcard"
Once we have fixed that we can implement the same verification logic on the client:
@model MyViewModel <script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script> <script type="text/javascript"> var isValidNumber = function (value, element, params) { var DELTAS = [0, 1, 2, 3, 4, -4, -3, -2, -1, 0]; var checksum = 0; for (var i = value.length - 1; i > -1; i--) { var j = value.charCodeAt(i) - 48; checksum += j; if (((i - value.Length) % 2) == 0) { checksum += DELTAS[j]; } } return (checksum % 10) == 0; }; jQuery.validator.addMethod('CreditCardtest', isValidNumber); jQuery.validator.unobtrusive.adapters.add('creditcard', { }, function (options) { options.rules['CreditCardtest'] = true; options.messages['CreditCardtest'] = options.message; }); </script> @using (Html.BeginForm()) { @Html.EditorFor(x => x.Number) @Html.ValidationMessageFor(x => x.Number) <button type="submit">OK</button> }
Obviously, all script elements fall into a separate file, and not inside the view. I just left it here for readability.
source share