英文:
Is it possible to add a custom validation message to my required field?
问题
我有一个带有一些InputText的EditForm。其中一些文本框是必填的,因此它们的类使用[Required]声明。但是,其中一些文本框还使用[StringLength(100, ErrorMessage = "Forename is too long")]声明。当文本框中的名字太长时,下面的消息是我写的'Forename is too long'。当我有一个RegularExpression [RegularExpression(@"^\w+[.]\w+[@]\w+[.]\w+$",
ErrorMessage = "Email must follow fred.example@live.com structure")].然后错误消息是'Email must follow fred.example@live.com structure'。所以我认为通过添加一些验证到[Required]来修改消息会很容易:[Required(ErrorMessage = "This is required")。但是显示的消息是'The Surname field is required'。我该如何编辑这个消息,因为我已经明显没有完成工作。
<InputText id="userForename" @bind-Value="newUser.Forename">
<InputText id="userSurname" @bind-Value="newUser.Surname">
<InputText id="userEmailAddress" @bind-Value="newUser.EmailAddress">
英文:
I have an EditForm with some InputText. Some of the textboxes are required and as such in their class are declared using the [Required]. However some of them also have a [StringLength(100, ErrorMessage = "Forename is too long")]. When the forename is too long in the textbox then the message below is as I have written it 'Forename is too long'. When I have a RegularExpression [RegularExpression(@"^\w+[.]\w+[@]\w+[.]\w+$",
ErrorMessage = "Email must follow fred.example@live.com structure")]. Then the error message is 'Email must follow fred.example@live.com structure'. So I though it would be easy to add some validation to the [Required] by putting : [Required(ErrorMessage = "This is required")]. However the message displayed is 'The Surname field is required.'. How can I edit this message because what I have done has clearly not done the job.
<EditForm Model=@newUser OnValidSubmit="HandleSubmit">
<DataAnnotationsValidator />
@* <ValidationSummary/>*@
<label for="userForename">Forename:</label>
<InputText id="userForename" @bind-Value="@newUser.Forename"></InputText>
<ValidationMessage For="@(() => newUser.Forename)" />
<label for="userSurname">Surname:</label>
<InputText id="userSurname" @bind-Value="@newUser.Surname"></InputText>
<ValidationMessage For="@(() => newUser.Surname)" />
<label for="userEmailAddress">Email Address:</label>
<InputText id="userEmailAddress" @bind-Value="@newUser.EmailAddress"></InputText>
<ValidationMessage For="@(() => newUser.EmailAddress)" />
<button type="submit" class="btn-primary">Add</button>
</EditForm>
答案1
得分: 1
我认为你应该为TextInput创建一个类。然后,在类中,你应该添加[Required(ErrorMessage = "错误消息")]
并删除<ValidationMessage For="@( () => newUser.Forename)" />
。然后,你可以删除@* <ValidationSummary/>*@
。
如果你想要更多信息,你可以访问这个链接。
英文:
I think you should create a class for the TextInput. Then, in the class, you should add [Required(ErrorMessage = "ERROR MESSAGE")]
and delete <ValidationMessage For="@(() => newUser.Forename)" />
. Then you can delete @* <ValidationSummary/>*@
.
If you want some more, you can visit this link
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论