I am having a problem with validation of an edit form in Blazor.
My form looks like this:
<EditForm Model="@FormModel" OnValidSubmit="@HandleValidSubmit" OnInvalidSubmit="@HandleInValidSubmit">
<DataAnnotationsValidator />
<div>
<InputText class="form-control" id="firstName" type="text" placeholder="First Name" @bind-Value="@FormModel.FirstName" />
<label for="firstName">First Name</label>
<ValidationMessage For="@(() => FormModel.FirstName)" />
</div>
</EditForm>
If I submit the form from one that started out empty, the validation works fine.
In my .cs
file I have:
FormModel = new FormUIModel();
The FormUIModel
has a required parameter
[Required(ErrorMessage = "First Name Required")]
public string? FirstName { get; set; }
This works fine.
But if I try and do it as an update, it does not validate. It goes directly to the OnValidSubmit
.
The only difference is that after I new up the FormModel
, I then populate it like this:
FormModel = new FormUIModel();
FormModel = await _service.GetFormData(rowId)
Even if I delete the data in the firstname
field, it will not show the “Required” message and never goes to the HandleInvalidSubmit
method.
Help is appreciated
I answered my own question.
I should not have done this..
<EditForm Model="@FormData" OnValidSubmit="@HandleValidSubmit" OnInvalidSubmit="@HandleInValidSubmit">
<DataAnnotationsValidator />
<div>
<InputText class="form-control" id="firstName" type="text" placeholder="First Name" @bind-Value="@FormData.FirstName" />
<label for="firstName">First Name</label>
<ValidationMessage For="@(() => FormData.FirstName)" />
</div>
</EditForm>
with my .cs being this instead….
FormData = new FormUIModel();
FormModel data = new FormModel();
data = await _service.GetFormData(rowId)
FormData.FirstName = !string.IsNullOrEmpty(data.FirstName) ? data.FirstName : null;