Search code examples
blazorblazor-client-side

Blazor: OnSubmit: How to access form input values and show ValidationMessage?


I know that when using OnSubmit for handling form submission (instead of OnValidSubmit and OnInvalidSubmit) we are responsible for ensuring that the form is valid (via calling EditContext.Validate() method);

Consider the following sample code:

<EditForm Model=@Person OnSubmit=@FormSubmitted>
  <DataAnnotationsValidator/>
  <ValidationSummary/>
  <div class="form-group">
    <label for="Name">Name</label>
    <InputText @bind-Value=Person.Name class="form-control" id="Name" />
    <ValidationMessage For="() => Person.Name"/>
  </div>
  <input type="submit" class="btn btn-primary" value="Save"/>
</EditForm>

Now suppose we are in the FormSubmitted function: My questions are:

  1. How can we access the value of the inputs of the from? (in the code above, accessing the value of the InputText with the id: "Name") (is data-binding the only way?)
  2. Since we are responsible for validating the form, the only way to show the ValidationMessage is to call EditContext.Validate() method (if form is indeed invalid) or we can decide and have control over which ValidationMessage to show up?

Solution

  • The issue you are facing is due to the fact that by the time EditContext.Validate returns, Validation has taken place, and validation messages are being displayed. Unfortunately, you can't do anything about it, especially because you cannot access and manipulate the ValidationMessageStore object where those messages are stored. Steve Anderson has told me that such feature will be provided, if more people (in addition to me) ask for it. I told him that this feature is very important... it was a couple of months ago, and you are not the first person to show that this feature is essential. You may go to github, and post an issue, requesting this feature made available.

    However, If you think you can't live with all the validation messages displayed at the same time ( some folks may say that it is desirable ), I guess you can do that implementing the ValidationMessage component to display only content you desire.

    If I were you, I wouldn't do that. It's usually more desirable to display messages for all the fields that need to be filled, and I guess that when users click on the submit button, they usually fill most of the fields.

    Hope this helps...