Per eseguire confronti tra maiuscole e minuscole, è possibile creare il proprio comparatore di confronto personalizzato. Finirai con questo.
public string Courriel { get; set; }
[EqualToIgnoreCase("Courriel", ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "E00007")]
public string CourrielConfirmation { get; set;}
Questa è la 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
}
Sul lato client si dovrà aggiungere questo semplice registrazione:
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;
});
fonte
2015-10-21 20:42:54
Avete considerato la validazione a distanza? Altrimenti potresti rimanere bloccato scrivendo un attributo di validazione, e CompareAttribute è uno dei più brutti. –
sì. Questa sembra un'opzione. Grazie. Ma c'è un altro modo ?, Così posso evitare questa chiamata ajax aggiuntiva. – user979737