Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String field length limitation and line breaks

Tags:

c#

asp.net-mvc

The scenario I have seems pretty common but I did not found good solution so far. So there's ASP.NET-MVC application with MSSQL database sitting in back-end. The model includes class A with string field Description that needs to be limited to 100 characters. It's declared as follows:

    [StringLength(100)]
    public virtual string Description { get; set; }

The corresponding column in the database is nvarchar with column length = 100. In the UI, Description field is represented by textarea with maxlength = 100.

Now the issue comes when there're line breaks in the textarea. They are interpreted as 1 character on client side but on server side they are represented by Environment.NewLine which is 2 characters (\r\n). So it exceeds the database column length (actually server side validation fails before the whole back-end thing but let's omit the validation for simplicity).

The solutions I found so far are:

  1. Add some magic on client side in order to interpret line break in textarea as two characters. I don't like this solution as it can confuse a user.
  2. Replace \r\n with \n on server side. Seems like a hack that could have some side effects.
  3. Remove/increase column length in the database. The simpliest one (without taking server-side validation issue into account) but let's say it's not the case.

I guess there should be something else besides those three.

like image 346
mayor Avatar asked Dec 16 '13 22:12

mayor


1 Answers

This is an old and known issue with MVC (I am not sure if it was solved) but different browsers treat line break differently. My suggestion is to custom model binder like what you find here jQuery validate textarea maxlength bug

like image 50
Raymund Avatar answered Oct 14 '22 00:10

Raymund