Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validation doesn't work on Blazor Server Side

I defined a form LogInForm.cs like this :

using System.ComponentModel.DataAnnotations;

namespace PollingInstitute.Data.LogIn
{
    public class LogInForm
    {
        [Required]
        [DataType(DataType.EmailAddress, ErrorMessage = "This field require a mail adress (example : [email protected])")]
        public string Mail { get; set; }

        [Required]
        [DataType(DataType.Password)]
        public string Password { get; set; }
    }
}

And a login screen LogIn.razor like this :

@page "/login"
@using PollingInstitute.Data.LogIn
@inject LogInService _LogInService

<h3>Login</h3>

<EditForm Model="@logInForm" OnValidSubmit="@TryLogIn">

    <div>
        <label>Mail Adress : </label><InputText @bind-Value="@logInForm.Mail"></InputText>
        <ValidationMessage For="@(()=>logInForm.Mail)"></ValidationMessage>
    </div>

    <div>
        <label>Password : </label><InputText @bind-Value="@logInForm.Password"></InputText>
        <ValidationMessage For="@(()=>logInForm.Password)"></ValidationMessage>
    </div>

    <div>

        @if (!IsDisabled)
        {
            <button type="submit">Submit</button>
        }
        else
        {
            <label>Please wait...</label>
        }
    </div>
    <ValidationSummary></ValidationSummary>
</EditForm>

@code {

    LogInForm logInForm = new LogInForm();
    protected bool IsDisabled { get; set; } = false;

    async void TryLogIn()
    {
        if (IsDisabled == true)
        {
            IsDisabled = true;
            StateHasChanged();
            bool result = (await _LogInService.TryLogIn(logInForm));
            Console.WriteLine("Logging status : " + (result ? "Sucess" : "Failure"));
            IsDisabled = false;
            StateHasChanged();
        }
    }

}

When I'm filling (or not) the fields, it's always indicating them as valid, even though it's supposed to be not valid.

I checked the _Imports.razor and it got the Microsoft.AspNetCore.Components.Forms library. I tried with Chrome and Firefox and it's always giving the same result. I checked if javascript was on, and it was.

So what I'm doing wrong ? Is there anything to do with my code ? Do I have to add something in the Startup.cs file ? I made a Blazor app as a tutorial using the validation system and it was working flawlessly.

like image 775
PepperTiger Avatar asked Nov 15 '19 12:11

PepperTiger


People also ask

How do you validate in Blazor?

You can define the form in a Blazor app using "EditForm" component. The Blazor engine only validates the input model's property value that is defined in "EditForm" component. The Blazor provides a DataAnnotationsValidator compoment that tells the Blazor engine to validate a model using data annotation.

How do you manually trigger the form validation in Blazor?

You have to define and bind the EditContext with EditForm and then call the method editContext. Validate() on button click to manually trigger the validation.

What is EditContext?

The EditContext is a new API that allows authors to more directly participate in the text input process.

How do I submit a form to Blazor?

You can submit a Blazor form programmatically by using EditContent validation. In the following example, a keypress event function triggers when you press the Enter key. It validates the form editContent. Validate() and submits the form programmatically.


1 Answers

I think the problem here is simply that you've forgotten to add the component which actually performs the validation. To fix that, add this line below your <EditForm Model="@logInForm" OnValidSubmit="@TryLogIn"> line:

      <DataAnnotationsValidator />

Also, the [DataType] attribute is for formatting rather than validation. The validation annotation for an email address is [EmailAddress], so add that too and it should work as expected. More on that here.

As a slight aside on this; I came from the WinForms world where validation often felt like an unknowable black box. In Blazor it's really well documented in the docs and also in the code, so if you want to learn more about it at any point it's actually possible. This blog by Steve Sanderson has some really good outline info in the "Blazor’s forms and validation extensibility" section.

like image 123
tomRedox Avatar answered Oct 21 '22 02:10

tomRedox