Skip to content

Instantly share code, notes, and snippets.

@timhobbs
Forked from michaeljacobdavis/Adapter.js
Created October 16, 2012 00:49
Show Gist options
  • Save timhobbs/3896651 to your computer and use it in GitHub Desktop.
Save timhobbs/3896651 to your computer and use it in GitHub Desktop.
NotEqual Fluent Validation validator with client side validation
(function ($) {
$.validator.addMethod("notequal", function (value, element, param) {
if (param.indexOf("#") == -1) return value != param;
return value != $(param).val();
}, $.validator.messages.notequal);
$.validator.unobtrusive.adapters.add("notequal", ["field"], function (options) {
options.rules["notequal"] = options.params.field;
if (options.message) options.messages["notequal"] = options.message;
});
})(jQuery);
FluentValidationModelValidatorProvider.Configure(provider =>
{
provider.Add(typeof(NotEqualValidator), (metadata, context, description, validator) => new NotEqualClientRule(metadata, context, description, validator));
});
@model Test.Models.PersonModel
@using (Html.BeginForm())
{
@Html.TextBoxFor(x => x.First)
@Html.ValidationMessageFor(x => x.First)
@Html.TextBoxFor(x => x.Last)
@Html.ValidationMessageFor(x => x.Last)
<button type="submit">OK</button>
}
[Validator(typeof(PersonValidator))]
public class PersonModel
{
public string First { get; set; }
public string Last { get; set; }
}
public class PersonValidator : AbstractValidator<PersonModel>
{
public PersonValidator()
{
RuleFor(x => x.First).NotEqual(x => x.Last);
}
}
public class NotEqualClientRule : FluentValidationPropertyValidator {
public static ModelValidator Create(ModelMetadata meta, ControllerContext context, PropertyRule propertyDescription, IPropertyValidator validator) {
return new NotEqualClientRule(meta, context, propertyDescription, validator);
}
public NotEqualClientRule(ModelMetadata metadata, ControllerContext controllerContext, PropertyRule propertyDescription, IPropertyValidator validator)
: base(metadata, controllerContext, propertyDescription, validator) {
ShouldValidate = false; //This is necessary - don't want to kick in during model binding.
}
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules() {
if (!this.ShouldGenerateClientSideRules()) {
yield break;
}
var validator = Validator as NotEqualValidator;
var errorMessage = new MessageFormatter()
.BuildMessage(validator.ErrorMessageSource.GetString());
var rule = new ModelClientValidationRule {
ErrorMessage = errorMessage,
ValidationType = "notequal"
};
if (validator.MemberToCompare != null) {
rule.ValidationParameters["field"] = String.Format("#{0}", validator.MemberToCompare.Name);
} else {
rule.ValidationParameters["field"] = validator.ValueToCompare;
}
yield return rule;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment