Home > Net >  Show validation message for razor view for input type number but model attribute string
Show validation message for razor view for input type number but model attribute string

Time:09-17

I have a string field in my modal class where users will have to enter numbers between 1-8 only. Modal class attribute:

[MaxLength(1)]
[MinLength(1)]
[Required(ErrorMessage = "Please enter correct value")]
public string RoomNumber { get; set; }

This input is asked in view page as::

<div class="form-group">
@Html.LabelFor(model => model.RoomNumber, htmlAttributes: new { @class = "col-md-12" })
<div class="col-md-12">
    @Html.EditorFor(model => model.RoomNumber, new { htmlAttributes = new { @class = "form-control input-digit", @type = "number", @min = "1", @max = "8" } })
    @Html.ValidationMessageFor(model => model.RoomNumber, "", new { @class = "text-danger" })
</div>
</div>
  1. I want to print validation message for the user if they enter incorrect value, I mean to show error message if they enter value greater than 8.

  2. Also can I restrict user input between 1 - 8 digit number only? Is it possible?

I can not change the data type of RoomNumber attribute due to project restrictions.

Thank You.

CodePudding user response:

In the example below the RegularExpression attribute is used to validate the RoomNumber property:

public class RoomInfo
{
    [RegularExpression(@"^[1-8]{1}$", ErrorMessage = "Enter valid number from 1 to 8"), Required]        
    public string RoomNumber { get; set; }
}

The view:

@model RoomInfo

@using (Html.BeginForm("Save", "Home"))
{
    @Html.ValidationSummary();

    <div class="form-group">
            @Html.LabelFor(m => m.RoomNumber)
            <p>@Html.TextBoxFor(m => m.RoomNumber, htmlAttributes: new { type="number", placeholder = "Room number" })</p>
            @Html.ValidationMessageFor(m => m.RoomNumber)
     </div>
    <button type="submit" class="btn btn-primary">Save</button>
}
  • Related