the stringLength() attribute defined in model class doesn't display validateion message when string size is over the limit

zbx888 20 Reputation points
2023-10-31T01:26:59.6866667+00:00

in my .net core razor page model class SRM I defined one string value as follows: [Column("NotFindingsConsistent")] [Display(Name = "If not consistent how were the finding different?")] [StringLength(250, ErrorMessage = "Comments must be less than 250 characters.")] public string NotFindingsConsistent { get; set; }

and its cshtml as follows: <div class="form-group row"> <label asp-for="SRM.NotFindingsConsistent" class="col-sm-4 col-form-label"></label> <div class="col-sm-8"> <textarea asp-for="SRM.NotFindingsConsistent" cols="100" rows="2"></textarea> <span asp-validation-for="SRM.NotFindingsConsistent" class="text-danger"></span> </div> </div>

When running the razor app, user enter data in tag <textarea> for NotFindingsConsistent over 250 characters and click save button, validation message doesn't pop up and cut off data to be 250 characters saving into DB. Why does the StringLength validation not work?

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,292 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Ping Ni-MSFT 2,795 Reputation points Microsoft Vendor
    2023-11-01T07:44:26.71+00:00

    Hi @zbx888,

    Use the asp-for together with StringLength data annotation will generate the html in the browser like below:

    <textarea cols="100" rows="2" data-val="true" data-val-length="Comments must be less than 250 characters." data-val-length-max="2" id="SRM_NotFindingsConsistent" 
      maxlength="250" name="SRM.NotFindingsConsistent" spellcheck="false" data-ms-editor="true"></textarea>
    

    You can see it generates the html with maxlength attribute. This attribute will limit the user type amount of characters without popping up the error message.

    If you want to display the error message, an alternative way is to avoid using asp-for tag helper, just use the name attribute:

    <textarea name="SRM.NotFindingsConsistent" cols="100" rows="2"></textarea>
    <span asp-validation-for="SRM.NotFindingsConsistent" class="text-danger"></span>
    

    Judge the ModelState in the backend and return page, it will display the error message when post back:

    public IActionResult OnPost()
    {
        if (!ModelState.IsValid)
        {
            return Page();
        }
    //....more code
        return Page();
    }
    

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Rena

    0 comments No comments