Solution 1: In Form 2 you can use OnSubmit
instead of OnValidSubmit
so the validation won't stop you. And in the method you passed to OnSubmit
you can do the validation yourself.
FormExample:
@(canSendData ? "Sent" : "Not sent")
@if (User is not null)
{
<EditForm Model="User" OnSubmit="Submit">
<DataAnnotationsValidator />
<label>Phone</label>
<InputText @bind-Value="User.Phone" />
<ValidationMessage For="@(() => User.Phone)" />
<label>Name</label>
<InputText @bind-Value="User.Name" />
<ValidationMessage For="@(() => User.Name)" />
<button class="btn btn-success" type="submit">Save</button>
</EditForm>
}
@code {
private bool canSendData;
[Parameter]
public User User { get; set; } = null!;
private void Submit(EditContext editContext)
{
var phoneFieldIdentifier = editContext.Field("Phone");
var nameFieldIdentifier = editContext.Field("Name");
editContext.NotifyFieldChanged(phoneFieldIdentifier);
var validationMessagesCount = editContext.GetValidationMessages().Count();
if (validationMessagesCount == 0)
{// every field is valid
canSendData = true;
StateHasChanged();
}
else if (validationMessagesCount == editContext.GetValidationMessages(nameFieldIdentifier).Count())
{// every field is valid except the field for the `Name` property, but we dont care about it
canSendData = true;
StateHasChanged();
}
else
{// there is/are some invalid field/s that we care about
canSendData = false;
StateHasChanged();
}
}
}
I tried it and it works- it validates and even shows validation messages!
Some links that provided info: Binding a form (docs) and this answer.
I would say that this solution is easy and fast to implement, but it has a downside... Let's say you fill the name field, click Save, but some field was invalid so it didn't send the data and showed the validation message... but before you click Save again, you (for some reason) decide that you don't want the name field to be filled anymore, so you delete its content, now you click Save and the problem has arrived... The validation message for Name
property shows. I don't know why but it does... On the other hand, even though the validation message shows the form will be saved. So it seems everything works "properly", BUT for some reason in this scenario the name field validation message is shown.
Solution 2: This another solution is more difficult to implement, but in my opinion it might be the most proper way how to do this- implementation of the custom validator. More here.
Bonus: While searching for info I came across this interesting blog post. It looks exactly like what you need but it says:
"If you use FluentValidation in a commercial project, please sponsor the project financially."