ASP.NET MVC客户端验证无法正常工作

时间:2014-10-26 07:40:56

标签: c# asp.net-mvc html5 asp.net-mvc-4 c#-4.0

出于某种原因 - MVC自定义客户端需要字段验证不起作用 - 这是我们的模型 -

public class PersonalDetailsViewModel : OnboardingViewModel
{
  [RequiredLocalized]
  public string FirstName { get; set; }
  ....
}

public class RequiredLocalizedAttribute : ValidationAttribute, IClientValidatable
{
    public override string FormatErrorMessage(string name)
    {
        return " This field is mandatory";
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (base.IsValid(value))
        {   
            return ValidationResult.Success;
        }
        return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        //string errorMessage = this.FormatErrorMessage(metadata.DisplayName);
        string errorMessage = ErrorMessageString;

        // The value we set here are needed by the jQuery adapter
        var requiredLocalizedRule = new ModelClientValidationRule
        {
            ErrorMessage = errorMessage,
            ValidationType = "requiredlocalized"
        };
        yield return requiredLocalizedRule;
    }
}    

  jQuery.validator.unobtrusive.adapters.add("requiredlocalized", function (options) {
        options.rules["requiredlocalized"] = "true";
    });
    jQuery.validator.addMethod("requiredlocalized", function (value) {
        return value.length > 0;
    });

当我在没有提供任何输入的情况下跳出此字段时

HTML输出

<input class="customText " data-val="true" data-val-length="Max length is 20 characters only"    
data-val-length-max="20" data-val-requiredlocalized="The field {0} is invalid." 
id="personalDetailsFirstName" maxlength="20" name="PersonalDetailsView.FirstName" 
title="firstName" type="text" value="" />

有没有人可以指导我出错的地方?。感谢您的帮助

0 个答案:

没有答案