I do not want to validate required but it validated in asp.netcore ?

mc 3,641 Reputation points
2022-08-24T02:03:43.487+00:00

I am using validation
.net core web
[MaxLength(50)] public string GraduateSchool { get; set; } = default!;

I do not want it be required.

but the html is :

<input type="text" class="form-control" data-val="true" data-val-maxlength="The field GraduateSchool must be a string or array type with a maximum length of '50'." data-val-maxlength-max="50" data-val-maxlength-max="50" data-val-required="The GraduateSchool field is required." id="GraduateSchool" maxlength="50" name="GraduateSchool" value="">

when I submit it will be an error.

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,140 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,246 questions
0 comments No comments
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 55,041 Reputation points
    2022-08-24T03:26:46.05+00:00

    Required tests that the field is not null. Your string is not nullable, so it’s required by default as a null value is not allowed. To make not required, make nullable:

    [MaxLength(50)] public string? GraduateSchool { get; set; } = default!;  
    

    See docs

    https://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-6.0

    Note: the browser posts no value for empty text fields.

    2 people found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful