如何显示用户名已经存在使用jQuery验证插件的验证?

时间:2019-01-11 07:25:10

标签: jquery asp.net-mvc

我已经搜索过此内容,但仅针对php就得到了答案。我需要 使用juqery验证插件验证asp.net mvc中的用户名是否已存在消息。我已经完成了对Name require的验证,该验证在模式弹出窗口上可以正常工作,但无法在已经存在的用户名上实现。

控制器:

if (ModelState.IsValid)
            {
                bool isUserExist = WebSecurity.UserExists(registerModel.Username);
                if (isUserExist)
                {
                    ModelState.AddModelError("Username", "UserName already exist");
                }

查看:

<div class="form-group">
            @Html.LabelFor(model => model.FullName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-8">
                @Html.EditorFor(model => model.FullName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.FullName, "", new { @class = "text-danger" })
            </div>
        </div>
<div class="form-group">
            @Html.LabelFor(model => model.Username, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-8">
                @Html.EditorFor(model => model.Username, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Username, "", new { @class = "text-danger" })
            </div>
        </div>

验证码

 $('#register').validate({

            rules: {
                FullName: {
                    required: true,

                },
                Username: {
                    required: true,

                }
            },
            messages: {
                Name: {
                    required: 'Name is required',
                    minlength: 'Minimum Length is 5',
                    maxlength: 'Maximum Length is 50'
                },
                Username: {
                    required: 'Username Require',
                     remote: "Email already in use!"
                }
            }
        })

1 个答案:

答案 0 :(得分:0)

您可以使用remote属性来验证服务器返回的结果。

  $( "#myform" ).validate({
  rules: {
    email: {
      required: true,
      email: true,
      remote: {
        url: "{Url for remote validation}",
        type: "post",
        data: {
          username: function() {
            return $( "#username" ).val();
          }
        }
      }
    }
  }
});

参考:https://jqueryvalidation.org/remote-method/