This is a migrated thread and some comments may be shown as answers.

TextBoxFor MaxLength using data annotations

1 Answer 1411 Views
TextBox
This is a migrated thread and some comments may be shown as answers.
Jason
Top achievements
Rank 1
Veteran
Jason asked on 11 May 2020, 10:51 PM

Is there a way to force the TextBoxFor component to honour the data annotation string/max length for a model property?

I have the following model property with a data annotation for StringLength.

 

[Required]
[StringLength(5)]
[Display(Name = "Name")]
public string Name { get; set; }

 

I'm using the TextBoxFor component in a view.  But it will NOT enforce the maximum string length during data entry.

 

In order to get the TextBoxFor to restrict the maximum string length, I have to add the @maxlength property myself.

 

@(Html.Kendo().TextBoxFor(m => m.Country.Name)
    .HtmlAttributes(new { @maxlength = "5" })
)

 

Is there a way to have the TextBoxFor enforce the string length based on the data annotation itself?

Thanks.

Jason

 

1 Answer, 1 is accepted

Sort by
0
Nikolay
Telerik team
answered on 14 May 2020, 01:09 PM

Hi Jason,

The DataAnnotation attributes are used by the Kendo UI Validator to create validation rules based on the unobtrusive HTML attributes. Those unobtrusive attributes are generated by ASP.NET Core, based on the data annotation attributes applied to the Model properties.

For example, setting this data annotation

[StringLength(5)]
public string LastName { get; set; }

will result in

But does not restrict the user input.

You can either set the @maxlength manually or switch the MaskedTextBoxEditorFor specifying a Mask property:

@(Html.Kendo().MaskedTextBoxFor(x => x)
    .Mask("LLLLL"))

Let me know if you have any questions.

Regards,
Nikolay
Progress Telerik

Progress is here for your business, like always. Read more about the measures we are taking to ensure business continuity and help fight the COVID-19 pandemic.
Our thoughts here at Progress are with those affected by the outbreak.
Tags
TextBox
Asked by
Jason
Top achievements
Rank 1
Veteran
Answers by
Nikolay
Telerik team
Share this question
or