MVC:自定义属性未在视图中填充

时间:2016-02-17 16:32:30

标签: asp.net-mvc

我正在编写一个自定义属性来验证名字和姓氏是否超过一定数量的字符,但错误信息的显示方式与开箱即用的注释不同。

这是我的实施。

public class User
{
    [Required(ErrorMessage = "Last Name is required.")]
    [RegularExpression(@"^[a-zA-Z'\s]{1,50}$", ErrorMessage = "Please enter a valid last name.")]
    [FullNameMaxLength("FirstName")]
    public string LastName { get; set; }
}


public class FullNameMaxLengthAttribute : ValidationAttribute
{
    private string _firstName;

    public FullNameMaxLengthAttribute(string firstName)
    {
        _firstName = firstName;
    }
    protected override ValidationResult IsValid(object lastName, ValidationContext validationContext)
    {
        clsUserRegistration userRegistrationContext = (clsUserRegistration)validationContext.ObjectInstance;

        if (lastName != null)
        {
            string strValue = lastName.ToString();
            PropertyInfo propInfo = validationContext.ObjectType.GetProperty(_firstName);

            if (propInfo == null)
                return new ValidationResult(String.Format("Property {0} is undefined.", _firstName));

            var fieldValue = propInfo.GetValue(validationContext.ObjectInstance, null).ToString();

            if (strValue.Length + fieldValue.Length > 53)
            {
                return new ValidationResult("First and last names are too long!");
            }

            return ValidationResult.Success;
        }

        return null;
    }
}

在我看来,我有一个ValidationMessageFor,它适用于非自定义属性。当我单步执行我的模型时,它返回ValidationMessage,但我看不到该错误消息。有什么想法吗?

1 个答案:

答案 0 :(得分:2)

以上只是“后端”验证。例如,当用户的浏览器关闭JavaScript时,该功能仍可正常工作 - 无论错误如何,页面都会回发,但会再次显示表单并附上验证消息。

对于“前端”验证,您需要这些内容:

public class FullNameMaxLengthAttribute : ValidationAttribute, IClientValidatable
{
    // Your Properties and IsValid method here

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule
        {
            ErrorMessage = String.IsNullOrEmpty(ErrorMessage) ? FormatErrorMessage(metadata.DisplayName) : ErrorMessage,
            ValidationType = "fullnamemaxlength"
        };

        rule.ValidationParameters["firstname"] = FirstName;
        rule.ValidationParameters["maxlength"] = 53;

        yield return rule;
    }
}

然后在添加到页面的JavaScript中:

if (jQuery.validator) {
    jQuery.validator.addMethod("fullnamemaxlength", function(value, element, param) {
    var name = param.firstname;
    var max = param.maxlength;
    return name.length > max;
});

jQuery.validator.unobtrusive.adapters.add("fullnamemaxlength", ["firstname", "maxlength"], function (options) {
        options.rules.fullnamemaxlength = {};
        options.rules.fullnamemaxlength.firstname = options.params.firstname;
        options.rules.fullnamemaxlength.maxlength = options.params.maximum;
        options.messages.fullnamemaxlength = options.message;
    }
);
}

请注意,它位于document.ready(){};

的OUTSIDE

这里类似的东西:client-side validation in custom validation attribute - asp.net mvc 4