I am using Ant design Blazor and trying to create a child component and apply validation as usual from the parent component. Below is my code.
Child component
<AntDesign.FormItem Label="@Label">
<AntDesign.InputNumber Step="Step" Min="Min" @bind-Value="@Amount" OnChange="OnAmountChanged"
TValue="double?" />
</AntDesign.FormItem>
@code {
[Parameter]
public string Label { get; set; }
[Parameter]
public double Step { get; set; }
[Parameter]
public double Min { get; set; } = double.MinValue;
[Parameter]
public double Max { get; set; } = double.MaxValue;
[Parameter]
public string Placeholder { get; set; }
[Parameter]
public double? Amount { get; set; }
[Parameter]
public EventCallback<double?> AmountChanged { get; set; }
private async Task OnAmountChanged(double? value)
{
await AmountChanged.InvokeAsync(value);
}
}
Parent component
<AntDesign.Content>
<AntDesign.Form LabelColSpan="8"
WrapperColSpan="16"
Model="@exchangeRate"
OnFinish="@OnFinish"
OnFinishFailed="@OnFinishFailed">
<Validator>
<FluentValidator TValidator="ExchangeRateValidator" />
</Validator>
<ChildContent>
<AntDesign.FormItem Label="Rate">
<AntDesign.InputNumber Step="0.1" Min="0" @bind-Value="context.Rate" Formatter="RateFormat" />
</AntDesign.FormItem>
<FormItem Label="Date">
<DatePicker TValue="DateTime?" Format="yyyy/MM/dd" @bind-Value="context.Date">
</DatePicker>
</FormItem>
<InputNumberComponent Label="Rate" @bind-Amount="context.Amount"></InputNumberComponent>
<Button Type="primary" HtmlType="submit">Submit</Button>
</ChildContent>
</AntDesign.Form>
</AntDesign.Content>
As can be seen, I am binding the value of Amount to the component directly using @bind-Amount. But, when I click on the Submit button, it triggers validation and displays the validation messages on the first two fields but not on the child component.
Any pointers?
A colleague of mine was able to help with the answer. We had to look into the Ant Design Blazor source for the FormItem to figure out what is happening and get the answer. To get the validation messages, Ant is depending on the validation messages in the EditContext but retrieving them using the Any input control's FieldIdentifier.
The FieldIdentifier is created by Ant using the ValueExpression of the control and not the value. When we set the value, from the child control, the Value taken as the ValueExpression and in turn, when looking for validation messages, it searches for error messages against Value and not the actual model field.
Setting the ValueExpression to a binding expression when binding to the child property fixed the issue.