首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用MudBlazor进行表单验证?

如何使用MudBlazor进行表单验证?
EN

Stack Overflow用户
提问于 2020-10-27 18:06:33
回答 1查看 2K关注 0票数 2

我已经用MudBlazor创建了一个漂亮的注册表。

代码语言:javascript
复制
     <MudCard Class="signup-form">
        <MudCardContent>
           <form>
            <MudTextField Label="Username" />
            <MudTextField Label="Email" />
            <MudTextField Label="Password" />
            <MudTextField Label="Repeat password" />
          </form>
        </MudCardContent>
        <MudCardActions>
            <MudButton Variant="Variant.Filled" Color="Color.Primary">Sign up</MudButton>
        </MudCardActions>
    </MudCard>

但是,当用户输入不充分或错误时,我如何显示验证错误?找不到有关如何在MudBlazor中执行此操作的信息。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-10-28 06:37:40

表单验证在MudBlazor Form documentation中有很好的文档记录。下面是你如何使用Blazor内置的验证机制,这对于你的用例来说可能是最简单的:

代码语言:javascript
复制
<EditForm Model="@model" OnValidSubmit="OnValidSubmit">
    <DataAnnotationsValidator />
    <MudCard Class="demo-form">
        <MudCardContent>
            <MudTextField Label="Username" HelperText="Max. 8 characters" @bind-Value="model.Username" For="@(() => model.Username)" />
            <MudTextField Label="Email" @bind-Value="model.Email" For="@(() => model.Email)" />
            <MudTextField Label="Password" HelperText="Choose a strong password" @bind-Value="model.Password" For="@(() => model.Password)" InputType="InputType.Password" />
            <MudTextField Label="Password" HelperText="Repeat the password" @bind-Value="model.Password2" For="@(() => model.Password2)" InputType="InputType.Password" />
        </MudCardContent>
        <MudCardActions>
            <MudButton ButtonType="ButtonType.Submit" Variant="Variant.Filled" Color="Color.Primary" Class="demo-form-button">Register</MudButton>
        </MudCardActions>
    </MudCard>    
</EditForm>

@code {
    RegisterAccountForm model = new RegisterAccountForm();

    public class RegisterAccountForm
    {
        [Required]
        [StringLength(8, ErrorMessage = "Name length can't be more than 8.")]
        public string Username { get; set; }

        [Required]
        [EmailAddress]
        public string Email { get; set; }

        [Required]
        [StringLength(30, ErrorMessage = "Password must be at least 8 characters long.", MinimumLength = 8)]
        public string Password { get; set; }

        [Required]
        [Compare(nameof(Password))]
        public string Password2 { get; set; }

    }

    private void OnValidSubmit(EditContext context)
    {
        // register the user
    }

}
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64552117

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档