开发者

In ASP.NET MVC 2, can you use data annotations to compare two fields in a form? What are the alternatives if not Data Annotations

开发者 https://www.devze.com 2023-02-07 21:50 出处:网络
I have two fields in my form AccountNumber ReverseAccountNumber Can i use data annotations to validate that the value of \"ReverseAccountNumber\" textbox is equal to the reversed value of \"开发者_开

I have two fields in my form

AccountNumber ReverseAccountNumber

Can i use data annotations to validate that the value of "ReverseAccountNumber" textbox is equal to the reversed value of "开发者_开发技巧AccountNumber".

i.e.

AccountNumber = 12345 ReverseAccountNumber = 54321

i expect the validation to occur on the lostFocus event of the ReverseAccountNumber textbox.

I think i can do this using IDataErrorInfo, However I believe this would require a POST first before validation occurs, and i consider it a last resort.


Simply add a validation attribute to the class (not the properties) and evaluate the class object to compare the two properties. As for the client side, ASP.NET MVC 3 should be able to generate proper client-side validation for this (although I have not tried it myself since Iam still using xVal).


CustomAttribute

[AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
public sealed class ReversStringMatchAttribute : ValidationAttribute
{
    public string Property { get; set; }        

    public ReversStringMatchAttribute()
    { }

    public override bool IsValid(object value)
    {
        return true;
    }
}

CustomValidator

public class ReversStringValidator : DataAnnotationsModelValidator<ReversStringMatchAttribute>
{
    string property;

    public ReversStringValidator(ModelMetadata metadata, ControllerContext context, ReversStringMatchAttribute attribute)
        : base(metadata, context, attribute)
    {
        property = attribute.Property;
    }

    public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
    {
        var rule = new ModelClientValidationRule
        {
            ErrorMessage = Attribute.ErrorMessage,
            ValidationType = "reversStringValidator"
        };

        rule.ValidationParameters.Add("propertyname", property);

        return new[] { rule };
    }
}

Java Script

Sys.Mvc.ValidatorRegistry.validators["reversStringValidator"] = function (rule) {
//initialization

//return validator function
return function (value, context) {
    var field = $get(rule.ValidationParameters['propertyname']);
    if (field == null)
        return "Property name is invalid!";

    var s1 = field.value;

    if (s1) {
        if (value) {
            var reverse = value.split("").reverse().join("");
            if (s1 != reverse.toString()) {
                return rule.ErrorMessage;
            }
        } else {
            return rule.ErrorMessage;
        }
    }

    return true;
}

};

then use it on your property

public class AccountViewModel
{
    [Required(ErrorMessage="Account Number is Required")]
    public string AccountNumber { get; set; }

    [ReversStringMatch(ErrorMessage = "The value doesn't match the Account Number", Property="AccountNumber")]
    public string ReverseAccountNumber { get; set; }            
}

i have some doubts on the $get validation method in javascript but it works, for now.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号