How do I prevent a user other than entering a whole number 1-9?

34 Views Asked by At

In this issue I am using C# ASP.NET Core 6.

I have an input in my model that I need to be entirely 1 digit from 1-9. I would like to not have to validate it in javascript since I have more validation that requires other fields based on this value or on a post-back.

In the model I have tried to make the property an int with the max length data-annotation, setting the min attribute to 1 and max attribute to 9, however it still allows them to enter larger numbers. I have tried making the property a string and putting the pattern="^[1-9]$" and they were able to enter special characters still.

The regular expression pattern in question (also shown in model property, and html pattern attribute): ^[1-9]$

I tried to show both ways I have tried to set it up.

Model Properties

[BindProperty, Display(Name = "Elapsed Days Level 1"), Range(1, 9, ErrorMessage = "Elapsed Days must be between 1-9 days"),]
public int ElapsedDaysLevel1 { get; set; } = 8;

[BindProperty, Display(Name = "Elapsed Days Level 2"), RegularExpression("^[1-9]$"), ]
public string ElapsedDaysLevel2 { get; set; } = Convert.ToString(9);

HTML

<input id="ElapsedDaysLevel1" asp-for="ElapsedDaysLevel1" type="number" min="1" max="9" aria-label="Elapsed Days One" class="form-control number-text-input-small inline-block-style button-control-disable"  />
<span class="inline-block-style"> TO </span>
<input id="ElapsedDaysLevel2" asp-for="ElapsedDaysLevel2" pattern="^[1-9]$"  aria-label="Elapsed Days Two" class="form-control number-text-input-small inline-block-style button-control-disable" max-length="1" />
0

There are 0 best solutions below