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

查看:95
本文介绍了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检查表单是否有效,并且返回true,则$("#formId").valid()意味着无论值的状态如何(有效与否),表单都是有效的.

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:

电子邮件已经存在

Email already exists

  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天全站免登陆