我对blazor服务器端的自定义组件有点问题。我尝试创建我的自定义DateTime组件。当我在enter上有可为null的输入时,一切都很好。我填写的姓名和表格仍然有效。当我在日期输入中写入无效内容时,它会显示验证是否正常。但当我删除无效值时,验证会被隐藏,但表单仍然无效。
@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;
}
}
}
在此处输入图像描述在此处输入图片描述在这里输入图片描述
谢谢你的帮助。
这是我的组件测试页面。只有当输入包含无效条目时,它才会报告验证错误。我看不出有什么问题,所以我认为你的表格有问题???
@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; }
}
}