Daniel
Daniel

Reputation: 393

Attribute [Required] not working on int for Form Input validation in Blazor?

The Required attribute does not seem to work on integer values. I also tried Range attribute on integer field and is behaving normal. The issues are that the validation is not made and the required message in front-end is not showing. For string values the attribute is behaving as expected. This is the sample code:

@page "/test"


<EditForm Model="@exampleModel">
    <DataAnnotationsValidator />
    <ValidationSummary />

        <InputNumber @bind-Value="exampleModel.Name2"></InputNumber>

        <button type="submit" value="Save" >
            Submit
        </button>

</EditForm>

@code {
    private ExampleModel exampleModel = new ExampleModel();


    public partial class ExampleModel
    {

        [Required]
        public string Name { get; set; }

        [Required]
        [Range(1, 100, ErrorMessage = "Error Test")]
        public int Name2 { get; set; }


    }
}

The Required attribute for Name is working while the one for Name2 is not. The Range attribute for Name2 is working as expected.

I'm using ASP.NET Core 3.1 with Visual Studio 16.9.4.

Upvotes: 2

Views: 3637

Answers (1)

Jason D
Jason D

Reputation: 2087

By default, the Name2 property is equal to ZERO. But because your allowed minimum is 1, you don't see the ZERO when the form loads.

Some solutions:

  1. Initialize Name2 to an integer value between 1 and 100 OR

  2. Declare Name2 as a nullable int

    public int? Name2 { get; set; }
    

Upvotes: 2

Related Questions