jdtcn / BlazorDateRangePicker

A Blazor component for choosing date ranges and dates
MIT License
186 stars 34 forks source link

Dynamic CSS on validation not applying. #47

Closed HassanFarishRasheed closed 3 years ago

HassanFarishRasheed commented 3 years ago

According to Microsoft Docs: https://docs.microsoft.com/en-us/aspnet/core/blazor/forms-validation?view=aspnetcore-5.0 Under heading: "InputText based on the input event" It mentions to add class="@CssClass" for dynamic CSS to work with form validation. I think this attribute is missing in your component. Upon validation it doesn't add "invalid" class to component and therefore it doesn't highlight the component in red outline even when its empty.

jdtcn commented 3 years ago

Hi.

Thank you for this feedback. Unfortunately, it's difficult to inherit DateRangePicker from InputText (or any other FormControl) because form control requires a cascading parameter of type EditContext. So we will be forced to use DateRangePicker inside an EditForm and it's not convenient at all.

But the good news is you can implement this form control yourself:

DpInput form control:

@inherits InputBase<DateRange>

<DateRangePicker class="@CssClass" 
                 StartDate="Value?.Start" EndDate="Value?.End" 
                 OnRangeSelect="OnRangeSelect" OnReset="OnReset" />

@code {
    private Task OnReset()
    {
        Value = null;
        return ValueChanged.InvokeAsync(Value);
    }

    private Task OnRangeSelect(DateRange range)
    {
        if (Value == null) Value = new DateRange();
        Value.Start = range.Start;
        Value.End = range.End;
        return ValueChanged.InvokeAsync(Value);
    }

    protected override bool TryParseValueFromString(string value, out DateRange result, out string validationErrorMessage)
    {
        result = new DateRange();
        validationErrorMessage = string.Empty;
        return false;
    }
}

And the usage is straightforward:

<EditForm Model="@exampleModel" OnValidSubmit="@HandleValidSubmit">
    <DataAnnotationsValidator />
    <ValidationSummary />

    <DpInput @bind-Value="@exampleModel.Range" />

    <button type="submit">Submit</button>
</EditForm>

<button @onclick="SetRange">Set value outside</button>

<p>Form value:</p>
<pre>@System.Text.Json.JsonSerializer.Serialize(exampleModel)</pre>

@code {

    private ExampleModel exampleModel = new ExampleModel();

    private void HandleValidSubmit()
    {

    }

    private void SetRange()
    {
        exampleModel.Range = new DateRange { Start = DateTime.Now.AddDays(-10), End = DateTime.Now };
    }

    public class ExampleModel
    {
        [Required]
        public DateRange Range { get; set; }
    }
}