Skip to content

Instantly share code, notes, and snippets.

@michaeljacobdavis
Created August 7, 2012 05:19
Show Gist options
  • Save michaeljacobdavis/3281907 to your computer and use it in GitHub Desktop.
Save michaeljacobdavis/3281907 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) {
return this.optional(element) || value != $(param).val();
}, "This has to be different...");
$.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 NotEqualPropertyValidator(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 NotEqualPropertyValidator : FluentValidationPropertyValidator
{
public NotEqualPropertyValidator(ModelMetadata metadata, ControllerContext controllerContext, PropertyRule rule, IPropertyValidator validator)
: base(metadata, controllerContext, rule, validator)
{
}
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
{
if (!ShouldGenerateClientSideRules()) yield break;
var formatter = new MessageFormatter().AppendPropertyName(Rule.PropertyName);
string message = formatter.BuildMessage(Validator.ErrorMessageSource.GetString());
var rule = new ModelClientValidationRule
{
ValidationType = "notequal",
ErrorMessage = message
};
rule.ValidationParameters["field"] = String.Format("#{0}", ((NotEqualValidator)Validator).MemberToCompare.Name);
yield return rule;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment