asp.net core unobtrusive validation fire on a non required field

789 Views Asked by At

I have a model with 2 fields and both are non required(no [Required] tag is used).

On the razor page I have unobtrusive and jquery validation js files included. When I do not fill any value and post the form I get an error(client side) that ask for the last field in my form is required.

I have searched but have not found similar issue, as there is no required tag in model/viewmodel then why this is required on client side.

[Update 1 : code added]

Model:

public class AppUser: IdentityUser
{
public string Name { get; set; }
public int Deposit { get; set; }
}

View:

<form method="post">
    <div class="form-group">
        <label asp-for="@Model.AppUser.Deposit" class="control-label"></label>
        <input asp-for="@Model.AppUser.Deposit" type="text" class="form-control" />
        <span asp-validation-for="@Model.AppUser.Deposit" class="text-danger"></span>
    </div>

    <div class="form-group">
        <label asp-for="@Model.AppUser.Email" class="control-label"></label>
        <input asp-for="@Model.AppUser.Email" type="text" class="form-control" />
        <span asp-validation-for="@Model.AppUser.Email" class="text-danger"></span>
    </div>
</form>

Controller:

public class SomeModel : PageModel
{
private readonly ApplicationDbContext _context;
private readonly UserManager<AppUser> _userManager;

[BindProperty]
public AppUser AppUser { get; set; }

public SomeModel(ApplicationDbContext context, UserManager<AppUser> userManager)
{
    _context = context;
    _userManager = userManager;
}

public async Task<IActionResult> OnGetAsync()
{
    //..some action
    return Page();
}

public async Task<IActionResult> OnPostAsync()
{
    //..some action
    return Page();
}
}
1

There are 1 best solutions below

0
Nima On

By default non-nullable types like int, double, byte, ... are required if you want them to be optional you have to use nullable type e.g. int?