MaxLength Attribute not generating client-side validation attributes

前端 未结 11 538
北荒
北荒 2020-11-30 02:41

I have a curious problem with ASP.NET MVC3 client-side validation. I have the following class:

public class Instrument : BaseObject
{
    public int Id { get         


        
相关标签:
11条回答
  • 2020-11-30 03:21
    <input class="text-box single-line" data-val="true" data-val-required="Name is required." 
        id="Name1" name="Name" type="text" value="">
    
    $('#Name1').keypress(function () {
        if (this.value.length >= 5) return false;
    });
    
    0 讨论(0)
  • 2020-11-30 03:22

    Try using the [StringLength] attribute:

    [Required(ErrorMessage = "Name is required.")]
    [StringLength(40, ErrorMessage = "Name cannot be longer than 40 characters.")]
    public string Name { get; set; }
    

    That's for validation purposes. If you want to set for example the maxlength attribute on the input you could write a custom data annotations metadata provider as shown in this post and customize the default templates.

    0 讨论(0)
  • 2020-11-30 03:23

    In MVC 4 If you want maxlenght in input type text ? You can !

    @Html.TextBoxFor(model => model.Item3.ADR_ZIP, new { @class = "gui-input ui-oblig", @maxlength = "5" })
    
    0 讨论(0)
  • 2020-11-30 03:26

    StringLength works great, i used it this way:

    [StringLength(25,MinimumLength=1,ErrorMessage="Sorry only 25 characters allowed for 
                  ProductName")]
    public string ProductName { get; set; }
    

    or Just Use RegularExpression without StringLength:

    [RegularExpression(@"^[a-zA-Z0-9'@&#.\s]{1,25}$", ErrorMessage = "Reg Says Sorry only 25 
                       characters allowed for ProductName")]    
    public string ProductName { get; set; }
    

    but for me above methods gave error in display view, cause i had already ProductName field in database which had more than 25 characters

    so finally i came across this and this post and tried to validate without model like this:

     <div class="editor-field">
     @Html.TextBoxFor(model => model.ProductName, new
     {
     @class = "form-control",
     data_val = "true",
     data_val_length = "Sorry only 25 characters allowed for ProductName",
     data_val_length_max = "25",
     data_val_length_min = "1"
     })
     <span class="validation"> @Html.ValidationMessageFor(model => model.ProductName)</span>
     </div>
    

    this solved my issue, you can also do validation manually using jquery or using ModelState.AddModelError

    hope helps someone.

    0 讨论(0)
  • 2020-11-30 03:26

    I know I am very late to the party, but I finaly found out how we can register the MaxLengthAttribute.

    First we need a validator:

    public class MaxLengthClientValidator : DataAnnotationsModelValidator<MaxLengthAttribute>
    {
        private readonly string _errorMessage;
        private readonly int _length;
    
    
        public MaxLengthClientValidator(ModelMetadata metadata, ControllerContext context, MaxLengthAttribute attribute)
        : base(metadata, context, attribute)
        {
            _errorMessage = attribute.FormatErrorMessage(metadata.DisplayName);
            _length = attribute.Length;
        }
    
        public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
        {
            var rule = new ModelClientValidationRule
            {
                ErrorMessage = _errorMessage,
                ValidationType = "length"
            };
    
            rule.ValidationParameters["max"] = _length;
            yield return rule;
        }
    }
    

    Nothing realy special. In the constructor we save some values from the attribute. In the GetClientValidationRules we set a rule. ValidationType = "length" is mapped to data-val-length by the framework. rule.ValidationParameters["max"] is for the data-val-length-max attribute.

    Now since you have a validator, you only need to register it in global.asax:

    protected void Application_Start()
    {
        //...
    
        //Register Validator
        DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(MaxLengthAttribute), typeof(MaxLengthClientValidator));
    }
    

    Et voila, it just works.

    0 讨论(0)
提交回复
热议问题