ASP.NET Core MVC validate not required fields
Asked Answered
I

2

9

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?

Inflate answered 14/9, 2019 at 19:21 Comment(1)
I believe you mean the IdArea field. it is an integerBrinkmanship
S
32

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?.

Schick answered 14/9, 2019 at 19:40 Comment(9)
I really set my property to Nullable and it worked, thanks. public int? IdArea { get; set; }Inflate
Can you tell me if there is any way to configure validations in ASP.NET Core to accept not nullable properties without having to change property in ViewModel?Inflate
@RenanBarbosa: The way it is implemented makes sense if you think about it. You cannot leave a value undefined that technically cannot be undefined. The Database would have to accept a null(=undefined) value as well. But if you use value type it would never be null. As you already know, the other way round it is possible. you can define properties of nullable types as required. I hope I explained understandable :)Schick
But for me, this doesn't work for strings. It says, Nullable Reference Type is not available for strings.Siltstone
OMG I have wasted almost 2 hours on this. Thank you!! Especially pointless because it's just a ViewModel field I was having a problem with.Michaelis
@poseidon String is already a nullable typeSchick
This works, i used "var errors = ModelState.Values.SelectMany(v => v.Errors);" to checked the message, it was "[0]: The ClassX field is required", so i use "?" on Classx propertie to solve this problem.Ericaericaceous
Had the same issue, suspected that's what it was; a quick Google search showed this question and answer, and Bob's your uncle!Jukebox
Whilst this answer is correct, there may be times whereby you don't want that property to be null on the model. On a get request you may populate that property, so that you can use it within your view, but on a post you may not care about that property. In this case you can use the [ValidateNever] attribute.Wisp
C
2

You can always use formnovalidate on any input you don't want validated.

<input asp-for="Numero" formnovalidate="formnovalidate" class="form-control" />

This way there is no need to change your model. This is demonstrated at W3Schools

Caducity answered 16/9, 2019 at 15:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.