MVC 5 远程验证 [英] MVC 5 Remote Validation

查看:34
本文介绍了MVC 5 远程验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在提交表单之前验证用户的输入字段值.

I need to validate an input field value from user before the form is submitted.

我在我的自定义控制器中创建了一个操作并用它装饰了该字段:

I have created an action in my custom controller and decorated the field with it:

动作名称:CheckValue控制器名称:Validate

action name: CheckValue controller name: Validate

[Remote("CheckValue", "Validate"), ErrorMessage="Value is not valid"]
public string Value { get; set; }

问题是当我按下提交时,正在提交表单,然后如果用户输入的值无效,则会显示消息 Value is not valid.

The problem is when I press submit, the form is being submitted and then the message Value is not valid is shown if the value entered by the user is not valid.

如何验证用户输入的值,并在值无效时阻止表单提交,并显示错误消息?

How can I validate the value entered by user and prevent the form to be submitted if value is not valid, and display the error message?

如果我尝试在 JavaScript 中检查表单是否有效 $("#formId").valid() 返回 true,这意味着无论值的状态如何(有效与否)表格有效.

If I try in JavaScript to check if the form is valid $("#formId").valid() that returns true, that means no matter what is the status of the value (valid or not) the form is valid.

另一方面,如果我用 [Required] 属性装饰另一个字段,则不会提交表单,并且会为该字段显示错误.但是,远程验证字段的验证不会在后台进行.

In the other hand if I decorate another field with the [Required] attribute the form is not submitted and the error is shown for that field that is required. However the validation doesn't occur behind the scene for the remote validation field.

推荐答案

MVC 中远程验证的完整解决方案.它将检查电子邮件是否存在于数据库中并显示以下错误:

The complete solution of Remote Validation in MVC. It will check if the email exists in database and show the following error:

电子邮件已存在

  1. 帐户控制器操作

[AllowAnonymous]
[HttpPost]
public ActionResult CheckExistingEmail(string Email)
{
    try
    {
        return Json(!IsEmailExists(Email));
    }
    catch (Exception ex)
    {
        return Json(false);
    }
}

private bool IsEmailExists(string email)
    =>  UserManager.FindByEmail(email) != null;

  • 添加模型验证

    [Required]
    [MaxLength(50)]
    [EmailAddress(ErrorMessage = "Invalid Email Address")]
    [System.Web.Mvc.Remote("CheckExistingEmail", "Account", HttpMethod = "POST", ErrorMessage = "Email already exists")]
    public string Email { get; set; }
    

  • 添加脚本

    <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
    

  • 这篇关于MVC 5 远程验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆