C# 如何在单击按钮时使用HTML表单验证?
我正在使用SyncFusion和Blazor创建一个应用程序。在此应用程序中,我有一个登录页面,如下所示: 使用此代码:C# 如何在单击按钮时使用HTML表单验证?,c#,html,forms,validation,blazor,C#,Html,Forms,Validation,Blazor,我正在使用SyncFusion和Blazor创建一个应用程序。在此应用程序中,我有一个登录页面,如下所示: 使用此代码: <EditForm Model="@ModelValue"> <SfTextBox @ref="user" Placeholder="E-mail" Created="@onCreateUser" CssClass="custom-login" Ty
<EditForm Model="@ModelValue">
<SfTextBox @ref="user" Placeholder="E-mail" Created="@onCreateUser" CssClass="custom-login" Type="InputType.Email" @bind-Value="@ModelValue.Email" required></SfTextBox>
<SfTextBox @ref="password" Placeholder="Password" Created="@onCreatePassword" CssClass="custom-login" Type="InputType.Password" @bind-Value="@ModelValue.Password" required minlength="7"></SfTextBox>
<SfCheckBox Label="Stay Signed In" @bind-Checked="rememberUser" CssClass="stay-signed-in-checkbox"></SfCheckBox>
<SfButton CssClass="forgot-password-button">Forgot Password?</SfButton>
<SfButton CssClass="login-button" OnClick="validateForm">LOGIN</SfButton>
</EditForm>
@code {
SfTextBox user;
SfTextBox password;
private bool rememberUser;
private User ModelValue = new User();
public void validateForm()
{
}
/*ICON*/
public void onCreateUser()
{
this.user.AddIcon("prepend", "oi oi-person");
}
public void onCreatePassword()
{
this.password.AddIcon("prepend", "oi oi-key");
}
}
忘记密码了?
登录
@代码{
SfTextBox用户;
SfTextBox密码;
私人布尔记忆者;
私有用户ModelValue=新用户();
公共void validateForm()
{
}
/*图标*/
public void onCreateUser()
{
此.user.AddIcon(“prepend”、“oi-oi-person”);
}
public void onCreatePassword()
{
此.password.AddIcon(“prepend”、“oi-oi-key”);
}
}
此表单中应用了html浏览器验证弹出窗口(自动)。在我的情况下,这些工作有点奇怪,因此我制作了一个视频插图:
正如您所看到的,电子邮件字段工作正常,每次按下按钮时都会进行html表单验证。在密码字段中,情况并非如此,至少需要7个字符,当我按submit按钮时,仅填写3个字符,我不会收到任何警告
有人知道如何解决这个问题吗?如果您想使用html5表单验证,
minlength
属性将不起作用。如果要进行验证,应该使用pattern
属性并像pattern=“.7,}”
一样传递它。这一点在本文中进行了解释
如果您想使用blazor验证(这是更好的,也是推荐的),您需要在User
模型中使用数据注释
对于特定情况,可以使用MinLength
属性
public class User
{
// other propeties
// Passing data annotations
[MinLength(7, ErrorMessage = "Password Min Length is 7")]
public string Password { get; set; }
}
要使数据注释验证生效,请不要忘记,您需要在EditForm
中包含DataAnnotationsValidator
组件
<EditForm Model="@ModelValue">
<DataAnnotationsValidator />
@* rest of components *@
</EditForm>
@*其余部件*@