<BitDatePicker @bind-Value="Model.Date"
AllowTextInput="true"
DateFormat="yyyy/M/d"
GoToToday="امروز" Placeholder="تاریخ را وارد کنید"
Culture="PersianCultureHelper.GetFaIrCultureByFarsiNames()"
Style="width:150px; display:inline-block;">
</BitDatePicker>
(https://i.stack.imgur.com/B45TB.png)
how to change(modify) the default validation message of this component?
I create a class that inherits from "ValidationAttribute" to override the error message by custom regex validation. but two messages show when the input is not valid.
I don't want to use "Require" attribute. it should show the message when the input is not valid.
CodePudding user response:
Not that simple. It's hard coded into the component.
However there is a way.
BitDatePicker
is a component that emulates a standard InputBase
type component, though it doesn't implement InputBase
. The validation message is generated in `TryParseValueFromString' which looks like this:
protected override bool TryParseValueFromString(string? value, [MaybeNullWhen(false)] out DateTimeOffset? result, [NotNullWhen(false)] out string? validationErrorMessage)
{
if (value.HasNoValue())
{
result = null;
validationErrorMessage = null;
return true;
}
if (DateTime.TryParseExact(value, DateFormat ?? Culture.DateTimeFormat.ShortDatePattern, Culture, DateTimeStyles.None, out DateTime parsedValue))
{
result = new DateTimeOffset(parsedValue, DateTimeOffset.Now.Offset);
validationErrorMessage = null;
return true;
}
result = default;
validationErrorMessage = $"The {DisplayName ?? FieldIdentifier.FieldName} field is not valid.";
return false;
}
So we can create a child component and override TryParseValueFromString
. Note that you have to "capture" the content generated in the parent and re-gurgitate it in the child.
MyBitDatePicker
@using System.Diagnostics.CodeAnalysis;
@inherits BitDatePicker
@this.ParentContent
@code {
public RenderFragment ParentContent;
public MyBitDatePicker()
{
ParentContent = (builder) => base.BuildRenderTree(builder);
}
/// <inheritdoc />
protected override bool TryParseValueFromString(string? value, [MaybeNullWhen(false)] out DateTimeOffset? result, [NotNullWhen(false)] out string? validationErrorMessage)
{
var isValid = base.TryParseValueFromString(value, out result, out validationErrorMessage);
//Custom message defined here
validationErrorMessage = $"The {DisplayName ?? FieldIdentifier.FieldName} field ain't right!";
return false;
}
}
You could prevent the problem in the first place by disabling AllowTextInput
. The user then can't select an invalid date.