使用自定义验证器对自定义类型属性进行客户端验证

时间:2014-10-31 18:51:01

标签: c# jquery asp.net-mvc-3 asp.net-mvc-4 unobtrusive-validation

我有一个棘手的要求,我必须比较两个自定义类类型的模型属性。服务器端验证是直接的,但使用jquery不引人注意的方式实现客户端验证尚不清楚。当mvc呈现html时,我没有看到附加的data-val属性

public class CommunicationViewModel
{
    public PhoneViewModel MobilePhone { get; set; }

    [ComparePhoneLocalized("CommunicationView.MobilePhone")]
    public PhoneViewModel ConfirmMobilePhoneNumber { get; set; }

    ........
    ........
}

public class PhoneViewModel
{
    public string Area { get; set; }
    public string Number { get; set; }
    public string Extension { get; set; }
    public string CountryCode { get; set; }
}

自定义验证器

[AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
public class CompareConditionalLocalizedAttribute : CompareAttribute, IClientValidatable
{
    private readonly object _typeId = new object();
    private const string ErrorMsg = "Rentered mobile number does not match the original";

    public string FieldName { get; set; }
    //public MessageManagement.MessageContext MessageContext { get; set; }
    //public MessageCode MessageCode { get; set; }
    public new string OtherProperty { get; set; }


    public CompareConditionalLocalizedAttribute(string otherProperty)
        : base(otherProperty)
    {
        OtherProperty = otherProperty;
    }

    public override string FormatErrorMessage(string name)
    {
        //** This error message will eventually be driven by resource provider factory **//
        return ErrorMsg;


        //var msg = Message.Create(MessageCode, MessageStatusType.Error, FieldName);

        //var messageRepository = ServeContext.Current.ResolveInstance<IMessageRepository>();
        //msg = messageRepository.MapMessage(msg, MessageContext);

        //return msg.MessageText;
    }

    protected override ValidationResult IsValid(object value, ValidationContext  
    validationContext)
    {
        if (String.IsNullOrEmpty(OtherProperty)) return null;

        var otherProperty = validationContext.ObjectType.GetProperty(OtherProperty);
        var compareTo = (string)otherProperty.GetValue(validationContext.ObjectInstance, null);
        if (value == null) return null;
        if (compareTo.Equals(value.ToString(), StringComparison.Ordinal))
        {
            return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
        }
        return ValidationResult.Success;
    }

    public new IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata 
        metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule
        {
            ErrorMessage = FormatErrorMessage(FieldName),
            ValidationType = "compareemail"
        };

        rule.ValidationParameters.Add("otherproperty", OtherProperty);
        yield return rule;
    }
}

JQuery Wire up

    jQuery.validator.unobtrusive.adapters.add("comparephone", "[otherproperty]", function 
         (options) {
            options.rules["comparephone"] = options.params.otherproperty;
            options.messages["comparephone"] = options.message;
        });
    jQuery.validator.addMethod("comparephone", function (value, element, params) {
            var compareTo = $('[name="' + params + '"]').val();
            if (value == compareTo) {
                return true;
            }
            return false;
        });

0 个答案:

没有答案