Saturday, April 26, 2014

Custom Email validation in Mvc


Create Model for Email validation. 

        [CustomValidation(typeof(RegisterModel), "CheckEmailRegistered")]
        [Remote("CheckEmailRegistered", "Common")]
        [Required(ErrorMessageResourceType = typeof(Global), ErrorMessageResourceName = "EmailRequired")]
        [Display(Name = "Email")]
        [EmailAddress(ErrorMessageResourceType = typeof(Global), ErrorMessageResourceName = "ValidEmailAddress", ErrorMessage = null)]
        [DataType(DataType.EmailAddress)]      
        public string Email { get; set; }


Create Action With the name of "CheckEmailRegistered" in "Common" Controller

  public virtual JsonResult CheckEmailRegistered(string email)
        {
            if (user != null && user.Email == email)
            {
                return Json(true, JsonRequestBehavior.AllowGet);
            }
            else
            {
                if (email != null)
                {
                    User chkUser = new User();
                    chkUser = UserUtil.FetchSingleUserByEmail(email);
                    if (chkUser != null)
                    {
                        return Json(true, JsonRequestBehavior.AllowGet);
                    }
                    else
                    {
                        return Json(false, JsonRequestBehavior.AllowGet);
                    }
                }
                else
                {
                    return Json(false, JsonRequestBehavior.AllowGet);
                }
            }
        }

No comments:

Post a Comment