dotnet / aspnetcore

ASP.NET Core is a cross-platform .NET framework for building modern cloud-based web applications on Windows, Mac, or Linux.
https://asp.net
MIT License
35.36k stars 9.99k forks source link

Get the element causing submit in EditContext.OnValidationRequested method #18326

Closed Kahbazi closed 4 years ago

Kahbazi commented 4 years ago

I'm writing a validation system for blazor and I want to validate my form based on how it get submitted. How can I achieve that?

Here's a sample of what I'm trying to do

@using FluentValidation;

<EditForm Model="@exampleModel">
    <InputNumber @bind-Value="exampleModel.Number" />
    <InputText @bind-Value="exampleModel.AcceptNote" />
    <InputText @bind-Value="exampleModel.RejectNote" />
    <button id="btnAccept" type="submit">Accept</button>
    <button id="btnReject" type="submit">Reject</button>
</EditForm>

@code {

    [CascadingParameter] public EditContext EditContext { get; set; }

    private ExampleModel exampleModel = new ExampleModel();

    protected override void OnInitialized()
    {
        EditContext.OnValidationRequested += (sender, args) =>
        {
            var validator = new ExampleModelValidator();
            var editContext = (EditContext)sender;

        // I want to know which element/component submit the form so I can choose the correct RuleSet

        validator.Validate(editContext.Model, ruleSet: "ACCEPT_OR_REJECT");
        };
    }

    public class ExampleModel
    {
        public string AcceptNote { get; set; }
        public string RejectNote { get; set; }
        public int Number { get; set; }
    }

    public class ExampleModelValidator : AbstractValidator<ExampleModel>
    {
        public ExampleModelValidator()
        {
            RuleSet("Accept", () =>
            {
                RuleFor(x => x.AcceptNote).NotNull();
                RuleFor(x => x.Number).GreaterThan(0);
            });

            RuleSet("Reject", () =>
            {
                RuleFor(x => x.RejectNote).NotNull();
                RuleFor(x => x.Number).GreaterThan(0);
            });
        }
    }
}

Describe the solution you'd like

I think the solution is that if it's possible somehow the element or component that causes Submit should be passed to EditForm.OnSubmit event, and then to EditContext.Validate and finally to EditContext.OnValidationRequested.

mrpmorris commented 4 years ago

When you say the element causing the submit, do you mean the button the user clicks to submit the form or something else?

mkArtakMSFT commented 4 years ago

Thanks for contacting us. A more idiomatic way to do this in Blazor would be for the event handler to be a lambda that passes a parameter from each case.