Email Validation in .Net mvc4 - c#

Currently I am using following code for email validation but
it does validate the dsgf#g mail id please help me
[Required(ErrorMessage = "Please Enter Email Id")]
[Display(Name = "Email-Id")]
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string Cust_Email { get; set; }

EmailAddress attribute will mark as valid the dsgf#g because it is a completely valid email address, so there is nothing wrong with that method. Consider the example username#localhost for example.
If it is not suits you then you can use regular expression ti set your own rule for validation. Try to use 'RegularExpression' attribute instead, something like:
[RegularExpression("^[^#\s]+#[^#\s]+(\.[^#\s]+)+$", ErrorMessage = "Invalid Email Address")]
public string Cust_Email { get; set; }
or
[RegularExpression(#"^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$", ErrorMessage = "Invalid Email Address")]
public string Cust_Email { get; set; }

the email is completely valid.
if you want to validate, simply don't use regex for validation. Send him a code to this email-address that he has to enter. email-addresses can now contain characters like ä,ö,ü,à,... this could be really difficult to match the correct one..
if you really want to validate it using regex you could take the RFC822 standard then:
you will find here: http://www.ex-parrot.com/pdw/Mail-RFC822-Address.html (have fun with this - didn't want to post, it's too long)

What about an extension method.
public static bool IsValidEmail(this string email)
{
bool rt = false;
try
{
var mail = new System.Net.Mail.MailAddress(email);
rt = mail.Host.Contains(".");
}
catch { }
return rt;
}

Related

How to validate error message using c# in asp.net mvc?

I am struggling to validate an empty EditorFor using Data-Annotation, have tried using jquery on a client side. Somehow I feel it's better to validate it from the back end than front end. Have a look and help me to improve my logic error. The idea I want this error to validate when user leaves the #EditorFor() showing error image.
// Model
[Required(ErrorMessage = "This field is required")]
public string Email { get; set; }
//View
script type='text/javascript'>
$(function () {
//When the blur event occurs from your Textbox (you lose focus)
$('#textEmail').blur(function () {
var email = document.getElementById("textEmail").value;
var expr = /^([\w-\.]+)##((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (!expr.test(email)) {
alert("Invalid email address.");
}
else {
alert("Ok");
}
});
});
It can be achieved without JQuery by using MVC's Data Annotation properly.
For data annotation, write error message above the property as below:
[Required(ErrorMessage = "This field is required")]
public string Email { get; set; }
Some other annotations are also available along with Required annotation. To validate the valid email address below annotation can be used:
[Required(ErrorMessage = "This field is required")]
[EmailAddress(ErrorMessage = "Invalid email address")]
public string Email { get; set; }

Validation for EmailAdress gets triggered for optional field

I have this email validation attribute
[EmailAddress]
[StringLength(50, ErrorMessage = "Email is too long!")]
public string Email { get; set; }
And it works fine, but the problem is when I type the email, and then erase it, the form still asks me to insert correct email even though the field is not required.
it will accept empty string or exact an email id
"^$|^([\w\.\-]+)#([\w\-]+)((\.(\w){2,3})+)$"
Answer

How can I send a Confirmation Email in asp.net mvc

Today i'm trying to follow this article of Shai Raiten's Blog and when I finish it the createStatus return invalidAnswer
here is my Register action
[HttpPost]
[AllowAnonymous]
[CaptchaValidation("CaptchaCode", "registerCaptcha", "Wrong captcha!")]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
MembershipCreateStatus createStatus;
Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, false, null, out createStatus);
if (createStatus == MembershipCreateStatus.Success)
{
MailHelper.SendConfirmationEmail(model.UserName);
return RedirectToAction("Confirmation", "User");
}
else
{
ModelState.AddModelError("", "Failed!");
}
}
return View(model);
}
and here is my RegisterModel.cs
public class RegisterModel
{
[Key]
public long ID { set; get; }
[Required(ErrorMessage = "Do not Skip this")]
public string UserName { set; get; }
[StringLength(500, MinimumLength = 6, ErrorMessage = "Atleast 6 characters in passwords")]
[Required(ErrorMessage = "Do not Skip this")]
public string Password { set; get; }
[Compare("Password", ErrorMessage = "Wrong confirm passwords")]
[Required(ErrorMessage = "Do not skip this")]
public string ConfirmPassword { set; get; }
public string Name { set; get; }
public string Address { set; get; }
[RegularExpression(#"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z", ErrorMessage = "This is not an email")]
public string Email { set; get; }
public string Phone { set; get; }
public bool EmailConfirm { set; get; }
}
any suggestion for me , really appreciated all the help you guys make.
The simplest thing you can do is:
First, you should define a property in your user model which will hold email confirmation token. Also, you should define property bool IsEmailConfirmed which defaults to false.
The token should be something like auto-generated random string. E.g. Guid.NewGuid().ToString()
Then, you should define another action, say [HttpGet, AllowAnonymous] ConfirmEmail(string email, string token), which will validate that token against saved in the database and update IsEmailConfirmed accordingly.
And the link you are asking about, should then point to an url which will look like something like that: http://YOUR.SERVER/YourController/ConfirmEmail?email={0}&token={1}, where {0} is user email and {1} is your user email confirmation token. It should return a view that tells whether confirmation was successfull.
However, i do recommend not to reinvent the wheel and to simply use Asp.Net Identity 2.0 framework, which will do all that authn & authz stuff for you.
Please follow the below example from ASP.Net site where its beautifully explained how to send email during registration prcoess.
http://www.asp.net/mvc/overview/security/create-an-aspnet-mvc-5-web-app-with-email-confirmation-and-password-reset
Additionally I would not recommend MD5 password hashinh since its pretty old, try using SHA 256 hashing for password encryption.
http://forums.asp.net/t/1211478.aspx?How+do+I+use+Sha256+to+Encrypt+a+String+

Setting up password/confirm password without [Compare]

I am using Asp.net MVC to create a password and confirm password field. I am currently using the remote attribute to check if password and confirm password are the same, however remote will only call a function if the box it is applied to is changed.
I've looked through previous posts going back to last year and found the most common suggestion to be the compare attribute, however it is now deprecated.
I assume there is a pre-built solution for this problem.
This is from the model
[Remote(UserController.ActionNameConstants.PasswordMatch,
UserController.NameConst, AdditionalFields = "ConfirmPassword",
ErrorMessage = "The passwords do not match")]
[MinLength(8, ErrorMessage="Minimum password length is 8")]
[DisplayName("Password"), RequiredIf("Id == 0",
ErrorMessage="Password is required")]
public string Password { get; set; }
[DisplayName("Confirm Password"), RequiredIf("Id == 0",
ErrorMessage = "Confirm password is required")]
public string ConfirmPassword { get; set; }
This is in the controller
[HttpGet]
public virtual JsonResult PasswordMatch(string password,string confirmPassword)
{
return this.Json(password ==
confirmPassword,JsonRequestBehavior.AllowGet);
}
Compare is not depricate you can still use [Compare("Property name to compare with")]... it's in "System.ComponentModel.DataAnnotations" namespace.

Passing a variable to validator

I am trying to set-up a remote validation similar to the one in this example:
Example
My application has a twist however, my form elements are dynamically generated, therefore this tag:
[Remote("doesUserNameExist", "Account", HttpMethod = "POST", ErrorMessage = "User name already exists. Please enter a different user name.")]
is not set in stone, I need to vary the ErrorMessage for example and preferably vary the action. Is it possible, or would you suggest taking the long-way, meaning to implement the whole ajax validation on my own.
Any suggestions are appreciated.
If you need to have a dynamic error message then you could return this as string from your validation action:
public ActionResult DoesUserNameExist(string username)
{
if (Exists(uasername))
{
string errorMessage = "Some dynamic error message";
return Json(errorMessage, JsonRequestBehavior.AllowGet);
}
return Json(true, JsonRequestBehavior.AllowGet);
}
And if you need even more flexibility such as invoking dynamic dynamic actions, then you're better of rolling your custom validation solution instead of relying on the built-in Remote attribute.
You can inherit from RemoteAttribute and make it fetch the required values from a service or factory according to your own logic. Here is an example:
[AttributeUsage(AttributeTargets.Property)]
public class MyRemoteAttribute : RemoteAttribute
{
public MyRemoteAttribute(Type type, string propertyName)
: base(MyRemoteAttributeDataProvider.GetAttributeData(type,propertyName).Action, MyRemoteAttributeDataProvider.GetAttributeData(type,propertyName).Controller)
{
var data = MyRemoteAttributeDataProvider.GetAttributeData(type,propertyName);
base.ErrorMessage = data.ErrorMessage;
base.HttpMethod = data.HttpMethod;
}
}
public static class MyRemoteAttributeDataProvider
{
public static RemoteAttributeData GetAttributeData(Type type
, string propertyName)
{
//this is where you are going to implement your logic im just implementing as an example
//you can pass in a different type to get your values. For example you can pass in a service to get required values.
//property specific logic here, again im going to implement to make this
//specification by example
var attrData = new RemoteAttributeData();
if(propertyName == "MyOtherProperty")
{
attrData.Action = "MyOtherPropertyRelatedAction";
attrData.Controller = "MyOtherPropertyRelatedController";
attrData.ErrorMessage = "MyOtherPropertyRelated Error Message";
attrData.HttpMethod = "POST";
}
else
{
attrData.Action = "UserNameExists";
attrData.Controller = "AccountController";
attrData.ErrorMessage = "Some Error Message";
attrData.HttpMethod = "POST";
}
return attrData;
}
}
public class RemoteAttributeData
{
public string Controller { get; set; }
public string Action { get; set; }
public string HttpMethod { get; set; }
public string ErrorMessage { get; set; }
}
And this is how you are supposed to use is:
public class RegisterViewModel
{
[Required]
[Display(Name = "User name")]
[MyRemote(typeof(RegisterViewModel),"UserName")]
public string UserName { 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; }
[Required]
[MyRemote(typeof(RegisterViewModel),"MyOtherProperty")]
public string MyOtherProperty { get; set; }
}
As I also mentioned above at the commentary. You should specialize that provider according to your needs.
I hope this helps.
UPDATE:
I update the implementation based on your comment, so that it takes a property name and does some property name specific wiring.

Categories