简体   繁体   中英

Blazor not working validations in custom component

i have a little problem with custom component in blazor server side. I try create my custom DateTime component. And when i have nullable input on enter is everything fine. I fill name and form is still valid. When i write something invalid to the date input, it's show me validation its ok. But when i delete the invalid value validation is hidden but form is still invalid.

@inherits InputBase<DateTime?>

<input value="@CurrentValue" @onchange="((v) => OnChange(v))" class="form-control" />
<ValidationMessage TValue="DateTime?" For="@ValueExpression" />


@code {
    public async Task OnChange(ChangeEventArgs changeEventArgs)
    {
        CurrentValueAsString = changeEventArgs.Value?.ToString();
        await Task.CompletedTask;
    }

    protected override bool TryParseValueFromString(string? value, [MaybeNullWhen(false)] out DateTime? result, [NotNullWhen(false)] out string validationErrorMessage)
    {
        if (string.IsNullOrWhiteSpace(value))
        {
            result = Value;
            validationErrorMessage = string.Empty;
            return true;
        }

        if (DateTime.TryParse(value, out DateTime output))
        {
            result = output;
            validationErrorMessage = string.Empty;
            return true;
        }
        else
        {
            result = null;
            validationErrorMessage = "Field hasn't right format";
            return false;
        }   
    }
}

enter image description here enter image description here enter image description here

Thank you for your help.

Here's my test page for your component. It only reports a validation error when the input contains an invalid entry. I can't see what's wrong, so I'm assuming there's a problem in your form???

@page "/"

<PageTitle>Index</PageTitle>

<EditForm EditContext=this.editContext OnInvalidSubmit=this.InvalidSubmit OnValidSubmit=this.ValidSubmit>
    Custom Date: <CustomDate @bind-Value=this.model.Date></CustomDate>
    <ValidationSummary />
    <button class="btn btn-success">Submit </button>
</EditForm>

@code {
    private Model model = new();
    private EditContext? editContext;

    private void InvalidSubmit()
    {
        var c = editContext?.Validate();
        var x = true;
    }

    private void ValidSubmit()
    {
        var c = editContext?.Validate();
        var x = true;
    }

    protected override void OnInitialized()
    {
        editContext = new EditContext(model);
        base.OnInitialized();
    }

    public class Model
    {
        public DateTime? Date { get; set; }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM