比较数据注释与确认密码不一致



我有一个简单的注册表单,它有密码确认,你只需重复密码,你就知道演练了。

现在,为了检查密码是否相同,我使用了名为Compare 的数据注释

[Required(ErrorMessage = "Password is required")]
[MinLength(4, ErrorMessage = "Must be at least 4 characters")]
[DataType(DataType.Password)]
public string Password { get; set; }
[Required(ErrorMessage = "Password confirmation is required")]
[MinLength(4, ErrorMessage = "Must be at least 4 characters")]
[DataType(DataType.Password)]
[Compare(nameof(Password), ErrorMessage = "Passwords should be the same.")]
public string PasswordConfirm { get; set; }

形式基本上是这样的:

<EditForm class="form-signin" OnValidSubmit="OnSubmit" Model="registerParameters">
<DataAnnotationsValidator />
<h4 class="font-weight-normal text-center">Create Account</h4>
<label for="inputUsername" class="sr-only">User Name</label>
<InputText id="inputUsername" class="form-control" placeholder="Username" autofocus @bind-Value="@registerParameters.UserName" />
<ValidationMessage For="@(() => registerParameters.UserName)" />
<label for="inputPassword" class="sr-only">Password</label>
<InputText type="password" id="inputPassword" class="form-control" placeholder="Password" @bind-Value="@registerParameters.Password" />
<ValidationMessage For="@(() => registerParameters.Password)" />
<label for="inputPasswordConfirm" class="sr-only">Password Confirmation</label>
<InputText type="password" id="inputPasswordConfirm" class="form-control" placeholder="Password Confirmation" @bind-Value="@registerParameters.PasswordConfirm" />
<ValidationMessage For="@(() => registerParameters.PasswordConfirm)" />
<button class="btn btn-lg btn-primary btn-block" type="submit">Create account</button>
<label class="text-danger">@error</label>
<NavLink href="login">
<h6 class="font-weight-normal text-center">Already have an account? Click here to login</h6>
</NavLink>
</EditForm>
@functions{
RegisterParametersDto registerParameters { get; set; } = new RegisterParametersDto();
dynamic dyn;
string error { get; set; }
async Task OnSubmit()
{
error = null;
try
{
await authStateProvider.Register(registerParameters);
navigationManager.NavigateTo("");
}
catch (Exception ex)
{
dyn = JsonConvert.DeserializeObject(ex.Message);
error = dyn.errorMessage;
}
}
}

现在,每当这些密码不匹配时,它都会正确显示错误消息,但当我尝试提交时,它会完全消失。我该怎么解决这个问题?

编辑:我要补充的是,compare注释是唯一一个这样操作的注释。如果密码确认太短,则会显示正确的错误,并且在按下提交按钮后不会消失。

从那以后,我为fluent验证更改了数据注释,它工作得很好,错误也消失了,所以我想这是使用fluent验证的另一个原因。

相关内容

  • 没有找到相关文章

最新更新