MVC 3 - Compare Attribute - Perform case insenstive comparision on Client side
Asked Answered
M

4

6

In the page I'm developing I have a "Email" field and "ConfirmEmail" field. And the requirement is to have a case insensitive comparision.

I could create a custom attribute and extend the behaviour of 'Compare' attribute that is inbuilt. This works on the serverside.

But I was not able to achieve it on client side. I'm sure that we have to do some additional things to make the unobtrusive jquery to do a case insensitive comparision.

Miscount answered 2/4, 2012 at 18:11 Comment(2)
Have you considered Remote validation? Otherwise you may be stuck writing a validation attribute, and the CompareAttribute is one of the ugliest.Ceria
yeah. This looks like an option. Thanks. But is there any other way?, So that i can avoid this additional ajax call.Miscount
M
2

You can use the compare attribute in MVC 3...which is a built in solution...

    [Compare("Email",ErrorMessage="your error message")]
    public string ConfirmEmail { get; set; }

Update: my bad probably I should have read your question better...anyways... for the unobtrusive way to work, after creating an attribute (the override version of Compare)... you need to do some javascript work for the unobtrusive client side validation to work...here is an example blog post unobtrusive client side validation with MVC 3 ...that does something similar to what I'm talking about...if you need further help...just ping back...I will be glad to help you with this...

Here is a more relevant post...which also talks about creating a custom attribute... Creating Custom Validation Attribute (Server side and Client Side)

Hope this helps...

Mondrian answered 2/4, 2012 at 18:21 Comment(1)
That first link is deadHelsell
C
1

I'm not entirely certain what you are looking for as far as the Compare attribute, but for the JavaScript, this will do the comparison and you can take action from the client based on the results.

if (email.toUpperCase() == confirmEmail.toUpperCase()) {
    alert("Emails are a match!");        
} else {
    alert("Emails do not match");
}
Contradict answered 3/4, 2012 at 18:34 Comment(0)
N
0

A bit late to the party, but I only just ran into a similar issue. This is being caused by an error in the jquery unobstrusive javascript file. A later version will fix it, I just ran

Install-Package jQuery.Validation.Unobtrusive

which installed v2, which works fine for me. Your mileage may vary.

This question has been properly answered here.

Nogas answered 9/10, 2013 at 7:11 Comment(0)
W
0

To perform case insensitive comparison you could create your custom compare validator. You will end up with this.

    public string Courriel { get; set; }

    [EqualToIgnoreCase("Courriel", ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "E00007")]
    public string CourrielConfirmation { get; set;}

This is the ValidationAttribute:

/// <summary>
/// The equal to ignore case.
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public class EqualToIgnoreCase : ValidationAttribute, IClientValidatable
{
    #region Constructors and Destructors
public EqualToIgnoreCase(string otherProperty)
    {
        if (otherProperty == null)
        {
            throw new ArgumentNullException("otherProperty");
        }

        this.OtherProperty = otherProperty;
    }

    #endregion

    #region Public Properties

    public string OtherProperty { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; private set; }

    #endregion

    #region Public Methods and Operators

   public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        ModelClientValidationRule compareRule = new ModelClientValidationRule();
        compareRule.ErrorMessage = this.ErrorMessageString;
        compareRule.ValidationType = "equaltoignorecase";
        compareRule.ValidationParameters.Add("otherpropertyname", this.OtherProperty);
        yield return compareRule;
    }

    #endregion

    #region Methods

   protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        PropertyInfo basePropertyInfo = validationContext.ObjectType.GetProperty(this.OtherProperty);

        IComparable valOther = (IComparable)basePropertyInfo.GetValue(validationContext.ObjectInstance, null);

        IComparable valThis = (IComparable)value;

        if (valOther.ToString().ToLower() == valThis.ToString().ToLower())
        {
            return ValidationResult.Success;
        }
        else
        {
            return new ValidationResult("Error");
        }
    }

    #endregion
}

On client side you will have to add this simple registration:

var isEqualToIgnoreCase = function (value, element, param) {
    return this.optional(element) ||
    (value.toLowerCase() == $(param).val().toLowerCase());
};

$.validator.addMethod("equaltoignorecase", isEqualToIgnoreCase);
$.validator.unobtrusive.adapters.add("equaltoignorecase", ["otherpropertyname"], function (options) {
    options.rules["equaltoignorecase"] = "#" + options.params.otherpropertyname;
    options.messages["equaltoignorecase"] = options.message;
});
Widower answered 21/10, 2015 at 20:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.