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

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; }

Related

ASP.NET Identity email fields - possible to add multiple emails in one field?

I have created an ASP.NET Web application using razor pages (not controllers) and this uses the Individual accounts from Identity.
The whole purpose of my site is that an admin logs in and uploads a document, they then press a button that sends an email to the receipting user to say they have a document to view.
I was wondering with microsoft identity, is there a possibility to use multiple emails? For example, putting a semi-colon between emails so that when the email is sent, it goes to multiple people.
The code im using behind the button to send the email is as follows:
using (var smtp = new System.Net.Mail.SmtpClient("ip address here"))
{
var emailMessage = new MailMessage();
emailMessage.From = new MailAddress("email#gmail.com");
emailMessage.To.Add(email);
emailMessage.Subject = "New Document Avaialable!";
emailMessage.Body = "You have a new purchase order available to view on the Portal!";
await smtp.SendMailAsync(emailMessage);
}
Fix as follows:
In the register.cshtml, there is an InputModel class that looks something along the lines of:
public class InputModel
{
[Required]
[DataType(DataType.Text)]
[Display(Name = "User Name")]
public string UserName { get; set; }
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
}
First of all, I removed the [EmailAddress] from above the email.
Then instead of a semi-colon in the email text box, i put a comma between each email address and it worked.

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

Email Validation in .Net mvc4

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;
}

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.

Validate model data

I have an issue regarding validating my model, depending on which text fields have a value. I have a simple model:
public class Person
{
[DisplayName("Forename")]
[Required(ErrorMessage = "Please enter a forename")]
public string Forename { get; set; }
[DisplayName("Surname")]
[Required(ErrorMessage = "Please enter a surname")]
public string Surname { get; set; }
[DisplayName("Country")]
[Required(ErrorMessage = "Please enter a country")]
public string Country { get; set; }
[DisplayName("Phone Number")]
[Required(ErrorMessage = "Please enter a phone number")]
public string Phone { get; set; }
[DisplayName("Mobile Number")]
[Required(ErrorMessage = "Please enter a mobile number")]
public string Mobile { get; set; }
}
In my view I display Forename, Surname, Country & Phone as text fields using the following code:
#Html.LabelFor(x => x.Forename)
#Html.TextBoxFor(x => x.Forename)
#Html.ValidationMessageFor(x => x.Forename)
If a user doesn't have a phone number, they click on a button and this reveals another text field for Mobile number. The "Phone" text field then gets reset. If the user enters a mobile number and then submits the form it fails. Is it possible to have a conditional statement in my model validation to only validate a property if another property doesn't have a value.
So if "Mobile" has a value, but "Phone" doesn't, validation will validate "Mobile" but ignore "Phone" and vice versa. Apologies if the last paragraph wasn't clear enough. Any help will be greatly appreciated.
You could always do the validation in the controller, Pseudo-code below
if (Condition)
{
ModelState.AddModelError("PropertyNameHere", "ErrorMessageHere");
}
Keep your view exactly as it is. Just remove the [Required()] tag from your model. You also want to add this code above the if (ModelState.IsValid) code.
You could do it manually with a simple check like:
if (ModelState.ContainsKey("Phone Number") && !ModelState.ContainsKey("Mobile Number"))
ModelState.Remove("Phone Number");
else if (!ModelState.ContainsKey("Phone Number") && ModelState.ContainsKey("Mobile Number"))
ModelState.Remove("Mobile Number");

Categories