2

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.

1
  • 1
    Name2 is an int (as opposed to int?) so it always going to have a value (0) and therefore required will not be flagged. Use int? if it is optional. Commented Apr 28, 2021 at 15:02

1 Answer 1

2

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; }
    
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.