如何远程验证邮件或检查邮件是否存在

本文关键字:是否 存在 检查 何远程 验证 | 更新日期: 2023-09-27 17:53:59

我试图检查电子邮件是否存在于注册,以便在数据库中没有重复的电子邮件。我正在使用MVC4默认互联网应用程序这样做,但我已经向RegisterviewModel添加了一个电子邮件字段。我也注意到,这是做得很好与用户名字段,但我不知道他们是如何做到的。我试图跟随这个博客下面,但没有运气,因为没有回应,当我点击创建。拉伯克。当我使用firebug时,当Json action excutes

时,我得到Status: 302 Found

这是我所拥有的:

UserProfile

[Table("UserProfile")]
public class UserProfile
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
    public string UserName { get; set; }
    public string Email { get; set; }
}

RegisterViewModel

public class RegisterModel
{
    [Required]
    [Display(Name = "User name")]
    public string UserName { get; set; }
    [Required]
    [DataType(DataType.EmailAddress)]
    [Display(Name = "Email")]
    [Remote("DoesUserEmailExist", "Account", HttpMethod = "POST", ErrorMessage = "Email address already exists. Please enter a different Email address.")]
    public string Email { get; set; }
    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.",      MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }
    [DataType(DataType.Password)]
    [Display(Name = "Confirm password")]
    [System.ComponentModel.DataAnnotations.Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }
}
<<p> 注册行动/strong>
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Register(RegisterModel model)
    {
        if (ModelState.IsValid)
        {
            try //CreateUserAndAccount
            {
                WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new { model.Email });
                WebSecurity.Login(model.UserName, model.Password);
                return RedirectToAction("Index", "Home");
            }
            catch (MembershipCreateUserException e)
            {
                ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
            }
        }
        // If we got this far, something failed, redisplay form
        return View(model);
    }
Json行动

[HttpPost]
    public JsonResult DoesUserEmailExist(string email)
    {
        var user = Membership.GetUserNameByEmail(email);
        return Json(user == null);
    }

Edit: add Register View

     @model Soccer.Models.RegisterModel
     @{
     ViewBag.Title = "Register";
     }
     <hgroup class="title">
     <h1>@ViewBag.Title.</h1>
     <h2>Create a new account.</h2>
     </hgroup>
 @using (Html.BeginForm()) {
 @Html.AntiForgeryToken()
 @Html.ValidationSummary()
 <fieldset>
    <legend>Registration Form</legend>
    <ol>
        <li>
            @Html.LabelFor(m => m.UserName)
            @Html.TextBoxFor(m => m.UserName)
        </li>
        <li>
            @Html.LabelFor(m => m.Email)
            @Html.TextBoxFor(m => m.Email)
        </li>
        <li>
            @Html.LabelFor(m => m.Password)
            @Html.PasswordFor(m => m.Password)
        </li>
        <li>
            @Html.LabelFor(m => m.ConfirmPassword)
            @Html.PasswordFor(m => m.ConfirmPassword)
        </li>
    </ol>
    <input type="submit" value="Register" />
</fieldset>
 }
 @section Scripts {
 @Scripts.Render("~/bundles/jqueryval")
 }

有我不应该做的事情,或者有其他更简单的选择,我可以在这里?

如何远程验证邮件或检查邮件是否存在

首先,我要感谢JOBG陪我度过这一切。如果您使用Database First,我在上面的问题中显示的内容应该仍然有效,因为它要求您在数据库中设置电子邮件列UNIQUE,但是为了使其与EF Code First一起工作,我必须对注册操作执行以下操作,还请注意,使用此解决方案,您不需要Remote Annotation in the model:

<<p> 注册行动/strong>
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Register(RegisterModel model)
    {
        if (ModelState.IsValid)
        {
            // Insert a new user into the database
            using (UsersContext db = new UsersContext())
            {
                UserProfile email = db.UserProfiles.FirstOrDefault(u => u.Email.ToLower() == model.Email.ToLower());
                try
                {
                    // Check if email already exists
                    if (email == null)
                    {
                        WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new { Email = model.Email });
                        WebSecurity.Login(model.UserName, model.Password);
                        return RedirectToAction("Index", "Home");
                    }
                    else
                    {
                        ModelState.AddModelError("Email", "Email address already exists. Please enter a different email address.");
                    }
                }
                catch (MembershipCreateUserException e)
                {
                    ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
                }
            }
        }
        // If we got this far, something failed, redisplay form
        return View(model);
    }

注意:请注意,此操作在UserName之前验证Email,并且要求您在创建对象之前至少访问数据库一次。

很难告诉没有视图代码,但我的第一个怀疑是js,确保你有jQuery验证插件设置到位,它应该触发验证与.blur()事件,检查页面与firebug(或类似),并寻找一个ajax POST击中DoesUserEmailExist当字段失去焦点,如果这没有发生,那么在客户端是缺少Remote属性和服务DoesUserEmailExist看起来不错。

边注 :确保您在数据库中有UNIQUE约束的电子邮件字段,这是唯一真正的方法,以确保您没有重复的电子邮件,即使与DoesUserEmailExist验证,因为并发性