为什么远程验证没有解雇

时间:2018-02-11 08:15:08

标签: jquery asp.net-mvc-4

我试图远程验证我的用户名,遗憾的是没有解雇 这是我的viewmodel代码

public class UsersNew
{
public IList<RoleCheckbox> Roles { get; set; }

[Required,StringLength(6,MinimumLength =3)]
[Remote("IsAvailable","Validation")]
[RegularExpression(@"(\S)+",ErrorMessage = "White space is not allowed.")]
public string username { get; set; }

[Required,DataType(DataType.Password)]
public string password { get; set; }

[Required,MaxLength(256),DataType(DataType.EmailAddress)]
public string email { get; set; }
}

我的控制器

public class ValidationController : Controller
{

public JsonResult IsAvailable(string username)
{
if (!Database.Session.Query<User>().Any(u => u.username == username))
return Json(true, JsonRequestBehavior.AllowGet);
 string suggestedUID = String.Format(CultureInfo.InvariantCulture, "{0} is 
not available ", username);

for (int i = 0; i < 100; i++)
{
 string altCandidate = username + i.ToString();
 if (!Database.Session.Query<User>().Any(u => u.username == altCandidate))
 {
 suggestedUID = string.Format(CultureInfo.InvariantCulture, "{0} is not 
 available. Try {1}", username,
  altCandidate);
 break;
 }

 }
 return Json(suggestedUID, JsonRequestBehavior.AllowGet);
 }
 }

我甚至包括默认的jquery验证

 @Scripts.Render("~/bundles/jquery")
 @Scripts.Render("~/bundles/jqueryval")

我在这里做错了什么?

1 个答案:

答案 0 :(得分:0)

在用户名模型中,我添加了错误消息&#34;用户名不可用&#34;

public class UsersNew
{
    [Required, StringLength(6, MinimumLength = 3)]
    [Remote("IsAvailable", "Validation", ErrorMessage = "Username is not available ")]
    [RegularExpression(@"(\S)+", ErrorMessage = "White space is not allowed.")]
    public string username { get; set; }

    [Required, DataType(DataType.Password)]
    public string password { get; set; }

    [Required, MaxLength(256), DataType(DataType.EmailAddress)]
    public string email { get; set; }
}

Controller必须返回&#34; True&#34;远程验证中的&#34; False&#34;

public JsonResult IsAvailable(string username)
{
    if (!Database.Session.Query<User>().Any(u => u.username == username))
    {
        return Json(true, JsonRequestBehavior.AllowGet);
    }

    for (int i = 0; i < 100; i++)
    {
        string altCandidate = username + i.ToString();
        if (!Database.Session.Query<User>().Any(u => u.username == altCandidate))
        {
            break;
        }
    }
    return Json(false, JsonRequestBehavior.AllowGet);
}

如果要显示自定义ErrorMessage,则使用$ Ajax POST请求POST用户名和获取结果,您可以显示它。

远程验证参考: - Remote Validation Sample