DarthVegan
DarthVegan

Reputation: 1269

Required value in MVC is empty string but modelstate is still valid

I have a required string for my model and I can submit the form and still leave the textbox blank and the model state is being returned as valid so I have no idea what I did wrong. This is the only control on my page that is doing this. Here is my code:

Model

[Required(ErrorMessage = "Requirements are Required.")]
[DataType(DataType.MultilineText, ErrorMessage = "Requirements is Required.")]
[StringLength(200, ErrorMessage = "200 Characters is the maximum allowed for requirements.")]
public string Requirements { get; set; }

View

<div class="form-group">
    @Html.LabelFor(model => model.Requirements, "Requirements:", htmlAttributes: new { @class = "col-sm-4 control-label" })
    <div class="col-sm-8">
        @Html.TextAreaFor(model => model.Requirements, htmlAttributes: new { @rows = "10", @cols = "50", @class = "form-control" })
        @Html.ValidationMessageFor(model => model.Requirements)
    </div>

Upvotes: 4

Views: 4401

Answers (1)

asdf_enel_hak
asdf_enel_hak

Reputation: 7650

Edit:
As @Stephen Muecke noted, I cant reproduce your case neither, it should be enough Required attribute. My answer below somehow Workaround as said by @MajkeloDev.


You should put MinimumLength = 10 for your field. number 200 indicates maximum length for your string

[StringLength(200, MinimumLength = 10, ErrorMessage = "200 Characters is the maximum allowed for requirements.")]

Note: MinimumLength = 10 is being some number for a meaningful input. For non empty string it is enough MinimumLength = 1

Upvotes: 2

Related Questions