Search code examples
asp.net-mvcasp.net-coreasp.net-core-mvcunobtrusive-validation

ASP.NET Core MVC validate not required fields


My page is validating a field that is not required when I submit, even though there is no validation configured for this field.

Create.cshtml

@model Lawtech.App.ViewModels.ProcessoViewModel

@{
    ViewData["Title"] = "Novo processo";
}

<h3 style="padding-top: 10px">@ViewData["Title"] </h3>

<hr />
<div class="row">
    <div class="col-md-12">
        <form asp-action="Create">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="row">
                <div class="form-group col-md-4">
                    <label asp-for="Numero" class="control-label"></label>
                    <input asp-for="Numero" class="form-control" />
                    <span asp-validation-for="Numero" class="text-danger"></span>
                </div>
                <div class="form-group col-sm-4">
                    <label asp-for="IdArea" class="control-label"></label>
                    <div class="input-group">
                        <select id="slcArea" asp-for="IdArea" class="form-control select2"></select>
                        <div class="input-group-btn">
                            <a asp-action="CreateArea" class="btn btn-info" style="border-radius:0 0.25rem 0.25rem 0" data-modal="">
                                <span class="fa fa-plus"></span>
                            </a>
                        </div>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="form-group col-md-6 mt-4">
                    <input type="submit" value="Cadastrar" class="btn btn-sm btn-primary" />
                    <a class="btn btn-sm btn-info" asp-action="Index">Voltar</a>
                </div>
            </div>
        </form>
    </div>
</div>

<div id="myModal" class="modal fade in">
    <div class="modal-dialog">
        <div class="modal-content">
            <div id="myModalContent"></div>
        </div>
    </div>
</div>

ViewModel

public class ProcessoViewModel
{
    [Key]
    public int Id { get; set; }

    [DisplayName("Número")]
    [Required(ErrorMessage = "O campo número é obrigatório")]
    public string Numero { get; set; }

    [DisplayName("Área")]
    public int IdArea { get; set; }     
}

Controller

In Controller Create method, nothing happens, because all validation takes place on the client side.

[Route("novo-processo")]
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(ProcessoViewModel processoViewModel)
{
    try
    {
        if (!ModelState.IsValid) return View(processoViewModel);

        await _processoBLL.Insert(_mapper.Map<ProcessoDTO>(processoViewModel));

        if (!ValidOperation()) return View(processoViewModel);

        return RedirectToAction(nameof(Index));
    }
    catch
    {
        return View();
    }
}

Inspecting in Chrome I see this generated html for the field that I didn't require validation, I don't know if it could be something related to Jquery.Unobtrusive but I can't remove it either because other fields will be validated.

<select id="slcArea" class="form-control select2 select2-hidden-accessible input-validation-error" data-val="true" data-val-required="The Área field is required." name="IdArea" data-select2-id="slcArea" tabindex="-1" aria-hidden="true" aria-describedby="slcArea-error" aria-invalid="true"></select>

Why is this validation taking place that I have not defined the field as required?


Solution

  • Not nullable properties (that is properties with value types) are always required. Use nullable types (reference types) for properties if they should not be required - eg. int?.