Не удается получить доступ к ValidationParameters при проверке на стороне клиента.NET MVC

Я пишу пользовательскую проверку для моего приложения.NET MVC 4. Это первая проверка, которая использует параметр, и я нахожу некоторые проблемы, чтобы получить это.

Это мой код C#:

ValidationAttribute:

namespace Validations
{
    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
    public class MinRequiredPasswordLengthValidationAttribute : ValidationAttribute, IClientValidatable
    {
        public MinRequiredPasswordLengthValidationAttribute()
        : base("The password is invalid")
        {

        }

        public override string FormatErrorMessage(string name)
        {
            return String.Format(CultureInfo.CurrentCulture, ErrorMessageString, name.ToLower(), Membership.MinRequiredPasswordLength);
        }

        public override bool IsValid(object value)
        {
            if (value == null || String.IsNullOrEmpty(value.ToString()))
            {
                return true;
            }

            return value.ToString().Length >= Membership.MinRequiredPasswordLength;
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            ModelClientMinRequiredPasswordLengthValidationRule rule = new ModelClientMinRequiredPasswordLengthValidationRule(FormatErrorMessage(metadata.GetDisplayName()), Membership.MinRequiredPasswordLength);
            yield return rule;
        }
    }
}

ModelClientValidationRule:

namespace Validations
{
    public class ModelClientMinRequiredPasswordLengthValidationRule : ModelClientValidationRule
    {
        public ModelClientMinRequiredPasswordLengthValidationRule(string errorMessage, int minRequiredPasswordLength)
        {
            ErrorMessage = errorMessage;
            ValidationType = "minrequiredpasswordlength";
            ValidationParameters.Add("minlength", minRequiredPasswordLength);
        }
    }
}

А вот код JS, моя проблема:

jQuery.validator.addMethod("minrequiredpasswordlength", function (value, element, params) {
    if (value.length == 0) {
        return true; //empty
}

return true; //dummy return
}, "");

jQuery.validator.unobtrusive.adapters.add("minrequiredpasswordlength", {}, function (options) {
    //XXX Here I should get the minlength parameter, but 'options' is a empty object
    options.messages["minrequiredpasswordlength"] = options.message;
});

Большое спасибо за помощь!

1 ответ

Решение

see if this link helps:

ASP.NET MVC 3 проверка на стороне клиента с параметрами

Кроме того, попробуйте изменить свой код JavaScript на это:

$.validator.addMethod('minrequiredpasswordlength', function (value, element, params) {
    var minLength = params.minLength;

    // minLength should contain your value.
    return true; // dummy return
});

jQuery.validator.unobtrusive.adapters.add('minrequiredpasswordlength', [ 'minlength' ], function (options) {

    options.rules['minrequiredpasswordlength'] = {
            minLength: options.params['minlength']
        };

    //XXX Here I should get the minlength parameter, but 'options' is a empty object
    options.messages["minrequiredpasswordlength"] = options.message;
});

Секрет здесь в том, чтобы использовать [ 'minlength' ] вместо {} Мне понадобилось много времени, когда я впервые узнал об этом. Надеюсь, это поможет.

Другие вопросы по тегам