English 中文(简体)
用户不提供任何投入领域的标签错误验证
原标题:Blazor validation errors without any input fields from the user

我正在编写一本书状,并有一个日历,注明日期为纽芬兰语,这样当用户点击所期望的支票或检查其自动填入我的模型的日期时。

我的问题是,当用户没有<输入代码>InputText的田地时,我会如何留下自己的验证错误?

// This iterated through the remaining days in the month to properly display the calendar
@for (int i = DateTime.Now.AddDays(1).Day; i <= daysInMonth; i++)
{
    DateTime date = new DateTime(calendarMonth.Year, calendarMonth.Month, i);

    <div class="active">
        <button @onclick="() => SetDate(DateOnly.FromDateTime(date))">@i</button>
    </div>
}

<EditForm Model="@booking" OnValidSubmit="CreateDates" FormName="CommitDates">
    <div class="contact-form-button span-all">
        <button type="submit" class="btn btn-main">Submit<i class="fa-solid fa-paper-plane btn-icon"></i></button>
    </div>

    <div class="span-all">
        <DataAnnotationsValidator />
        <ValidationSummary />
    </div>
</EditForm>

@code {
    [Parameter]
    public int daysInMonth { get; set; }

// status parameter just checks whether we are modifying the check in or check out date value
    [Parameter]
    public bool status { get; set; }

    [Parameter]
    public DateOnly calendarMonth { get; set; }

    [Parameter]
    public BookingDatesVM booking { get; set; }

    protected override Task OnInitializedAsync()
    {
        return base.OnInitializedAsync();
    }

    private void SetDate(DateOnly date)
    {
        if (status)
        {
            booking.CheckInDate = date;
        }
        else
        {
            booking.CheckOutDate = date;
        }
    }

    private async Task CreateDates()
    {
        //await _bookingRepository.Create(booking);
    }
}

This is my model, the session id is stored using ProtectedSessionStorage and retrieved from the parent component and passed into this child component.

public class BookingDatesVM
{
    [Required]
    public Guid SessionId { get; set; }

    [Required]
    public DateOnly CheckInDate { get; set; }

    [Required]
    public DateOnly CheckOutDate { get; set; }

    public Status BookingStatus { get; set; }
    public DateTime CreatedDate { get; set; }

    public enum Status
    {
        InProcess,
        Pending,
        New,
        Approved,
        Declined,
        Cancelled
    }
}

I have tried to research this issue and tried some EditContext material i saw on here but still didn t give me any output regarding the errors. I also tried adding the text boxes and populating them with the values but that also did not work.

最佳回答

根据您的法典编写的样本:

@for (int i = DateTime.Now.AddDays(1).Day; i <= daysInMonth; i++)
{
    DateTime date = new DateTime(calendarMonth.Year, calendarMonth.Month, i);

    <div class="active">
        <button @onclick="() => SetDate(DateOnly.FromDateTime(date))">@i</button>
    </div>
}


<EditForm EditContext="editContext" OnValidSubmit="CreateDates" FormName="CommitDates">
     <div class="span-all">
        <DataAnnotationsValidator />
        <ValidationSummary />
    </div>
    
    <div class="contact-form-button span-all">
        <button type="submit" class="btn btn-main">Submit<i class="fa-solid fa-paper-plane btn-icon"></i></button>
    </div>

    
</EditForm>

@code {
    [Parameter]
    public int daysInMonth { get; set; } = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month);

    // status parameter just checks whether we are modifying the check in or check out date value
    [Parameter]
    public bool status { get; set; }

    [Parameter]
    public DateOnly calendarMonth { get; set; }

    [Parameter]
    public BookingDatesVM booking { get; set; }
    

    private EditContext? editContext;

    private ValidationMessageStore? messageStore;

    protected override Task OnInitializedAsync()
    {
        booking = new();
        editContext = new(booking);
        editContext.OnValidationRequested += HandleValidationRequested;
        messageStore = new(editContext);
        return base.OnInitializedAsync();
    }

    public void Dispose()
    {
        if (editContext is not null)
        {
            editContext.OnValidationRequested -= HandleValidationRequested;
        }
    }

    private void SetDate(DateOnly date)
    {
        if (status)
        {
            booking.CheckInDate = date;
        }
        else
        {
            booking.CheckOutDate = date;
        }
    }

    private async Task CreateDates()
    {
        //await _bookingRepository.Create(booking);
    }

    private void HandleValidationRequested(object? sender,
        ValidationRequestedEventArgs args)
    {
        messageStore?.Clear();

        // Your validation logic
        if (booking.CheckOutDate.DayNumber > DateTime.Now.Day+5)
        {
            messageStore?.Add(()=>booking.CheckOutDate, "Your  Error");
        }
    }

}

结果:

“entergraph

问题回答

Thank you @Ruikai for answering and it was very helpful. Essentially I used your idea and improvised on it a little.

我将EditForm标签改为:

<EditForm OnSubmit="CreateDates" EditContext="editContext">
    <div>
        <button type="submit" class="btn btn-main">Book Dates<i class="fa-regular fa-calendar-check btn-icon"></i></button>
    </div>

    <div>
        <DataAnnotationsValidator />
        <ValidationSummary />
    </div>
</EditForm>

在我试图利用EditForm的EditContext时,我有《示范公约》和《EditContext》的属性,并且将《OnValid Submit》改为《创造就业机会的方法》。

在创作方法中,我使用EditContext处理所有必要的鉴定。 这里是我的创建方法:

private async Task CreateDates()
{
    valid = editContext.Validate();
    validationMessages?.Clear();

    var checkOutDate = editContext.Field(nameof(booking.CheckOutDate));
    var checkInDate = editContext.Field(nameof(booking.CheckInDate));

    if (booking.CheckInDate == DateOnly.MinValue)
    {
        validationMessages.Add(checkInDate, "Check in date is required.");
        valid = false;
    }
    if (booking.CheckOutDate == DateOnly.MinValue)
    {
        validationMessages.Add(checkOutDate, "Check out date is required.");
        valid = false;
    }

    valid = editContext.Validate();
    //await _bookingRepository.Create(booking);
}

Hopefully this helps as an alternative answer.





相关问题
Manually implementing high performance algorithms in .NET

As a learning experience I recently tried implementing Quicksort with 3 way partitioning in C#. Apart from needing to add an extra range check on the left/right variables before the recursive call, ...

Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

How do I compare two decimals to 10 decimal places?

I m using decimal type (.net), and I want to see if two numbers are equal. But I only want to be accurate to 10 decimal places. For example take these three numbers. I want them all to be equal. 0....

Exception practices when creating a SynchronizationContext?

I m creating an STA version of the SynchronizationContext for use in Windows Workflow 4.0. I m wondering what to do about exceptions when Post-ing callbacks. The SynchronizationContext can be used ...

Show running instance in single instance application

I am building an application with C#. I managed to turn this into a single instance application by checking if the same process is already running. Process[] pname = Process.GetProcessesByName("...

How to combine DataTrigger and EventTrigger?

NOTE I have asked the related question (with an accepted answer): How to combine DataTrigger and Trigger? I think I need to combine an EventTrigger and a DataTrigger to achieve what I m after: when ...

热门标签