Model Validation using StringLength validation attribute

6.9k views Asked by At

In my ASP.NET MVC Core 1.1.1 I've a form with one input as follows where user is required to enter the district code as two characters such as 01, 02,...10,11, etc. But when I submit the form by entering district code as, say, 123, it still successfully submits the form without forcing user to enter the district code as two characters. What I may be missing?

MyViewModels

...
[Display(Name = "District"),StringLength(2)]
public string Dist { get; set; }
...

Form

@model MyProj.Models.MyViewModel
...
<div class="form-group">
    <label asp-for="Dist" class="col-md-2 control-label"></label>
    <div class="col-md-2">
        <input asp-for="Dist" class="form-control" />
        <span asp-validation-for="Dist" class="text-danger"></span>
    </div>
    <div class="col-sm-pull-8">01 to 53 — district codes</div>
</div>
...

NOTE I am using default ASP.NET Core Web Application template with latest version of VS2017 that by default installs necessary Bootstrap and other javascripts when one uses such template.

1

There are 1 answers

0
SolidSk On

1 - The first parameter of StringLength is Maximum length. To define minimum you can do:

    [Display(Name = "District")]
    [Required]
    [StringLength(2, MinimumLength = 2)]
    public string Dist { get; set; }

or:

    [Display(Name = "District")]
    [Required]
    [MinLength(2)]
    [MaxLength(3)]
    public string Dist { get; set; }
  1. The Required attribute is missing!

View

Validation script:

@section Scripts { @Html.Partial("_ValidationScriptsPartial") }

Controller

[HttpPost]
    public IActionResult Contact(MyViewModel model)
    {
        if (ModelState.IsValid)
        { ... }