【问题标题】:How can I do form validation with MudBlazor?如何使用 MudBlazor 进行表单验证?
【发布时间】:2021-02-09 14:16:45
【问题描述】:

我用 MudBlazor 构建了一个漂亮的注册表单。

     <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 中找不到有关如何执行此操作的信息。

【问题讨论】:

    标签: forms validation blazor mudblazor


    【解决方案1】:

    表单验证在MudBlazor Form documentation 中有详细记录。以下是使用 Blazor 内置验证机制的方法,这对于您的用例来说可能是最简单的:

    <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
        }
    
    }
    

    【讨论】:

    猜你喜欢
    • 2021-10-22
    • 1970-01-01
    • 2023-03-30
    • 2018-05-11
    • 2015-06-25
    • 2017-02-04
    • 2015-07-31
    • 2023-03-15
    • 1970-01-01
    相关资源
    最近更新 更多