Is there a way using MVC data validation attributes to validate client side if two fields on my model are equal.
I have two fields:
[Required(ErrorMessage = "*")]
[Email(ErrorMessage = "*")]
public string Email { get; set; }
[Required(ErrorMessage = "*")]
[Email(ErrorMessage = "*")]
public string ConfirmEmail { get; set; }
I want to be able to add an attribute that those two fields should be equel and if not an validatio error will appear. Is there a way to do so?
Thank you.
Yep - for example:
[Compare("Email", ErrorMessage = "The email and confirmation do not match.")]
Hope that helps.
Take a look at the CompareAttribute
[Compare("Email", ErrorMessage = "The email and confirmation email do not match.")]
public string ConfirmEmail { get; set; }
Related
In register form I use EmailAddress attribute to validate user email.
public class RegisterViewModel
{
[Required(ErrorMessage = "Pole wymagane")]
[Display(Name = "Email")]
[DataType(DataType.EmailAddress)]
[EmailAddress]
public string Email { get; set; }
}
Is there any chance to show what is wrong with email address if validation fails? For example 'oops, I see that your email address contains whitespace'
You have to add another validation for that. Example using [RegularExpression]
public class RegisterViewModel
{
[Required(ErrorMessage = "Pole wymagane")]
[RegularExpression(#"^\S*$", ErrorMessage = "Email Address cannot have white spaces")]
[Display(Name = "Email")]
[DataType(DataType.EmailAddress)]
[EmailAddress]
public string Email { get; set; }
}
You can define your own regular expression for email:
// built-in [EmailAddress] does not allow white spaces around email
public const string EmailValidationRegEx = #"^\s*\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*\s*$";
Note: I have just added white spaces around the existing .NET regex pattern for email match:
"^\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$"
Now you can use this new regex pattern instead of [EmailAddress] attribute:
public class RegisterViewModel
{
private string _email;
[Required(ErrorMessage = "Pole wymagane")]
[Display(Name = "Email")]
[DataType(DataType.EmailAddress)]
[RegularExpressionWithOptions(EmailValidationRegEx, ErrorMessage = "Invalid email")]
public string Email
{
get
{
if (!string.IsNullOrEmpty(_email))
{
return _email.Trim();
}
return string.Empty;
}
set
{
_email = value;
}
}
}
Note that I have modified the getter and return _email.Trim(), this ensures that we always get rid of extra white spaces before using the email value.
This question already has answers here:
Email address validation using ASP.NET MVC data type attributes
(12 answers)
Closed 8 years ago.
I want to force users to register with their e-mail addresses DataType.EmailAddress doesn't work.
public class RegisterModel
{
[Required]
[Display(Name = "E-mail")]
[DataType(DataType.EmailAddress)]
public string UserName { get; set; }
...
}
Any help is appreciated.
If your wanting validation for an email address, you need the [EmailAddress] attribute (NET 4.5)
[Required]
[Display(Name = "E-mail")]
[EmailAddress] // Add this
public string UserName { get; set; }
or for NET 4.0 you can use a [RegularExpression] attribute (this one is taken from jquery-validate 1.9.0)
[Required]
[Display(Name = "E-mail")]
[RegularExpression(#"^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$", ErrorMessage="Please enter a valid email adress")]
public string UserName { get; set; }
Note the [DataType] attributes are used by #Html.EditorFor() to render the type attribute used by browsers (e.g type="email")
You can use the "EmailAddress" annotation:
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string UserName { get; set; }
EDIT:
For MVC 4 and below, you can use regex expression to do validation on Email address fields.
See more here:
http://www.mkyong.com/regular-expressions/how-to-validate-email-address-with-regular-expression/
Hi I am using entity framework code first approach for my project.
i have a class called Login as shown below
public class Login
{
[Required(ErrorMessage = "UserName Required")]
[DisplayName("Username")]
[Key]
public string Username { get; set; }
[DataType(DataType.Password)]
[Required(ErrorMessage = "Password Required")]
[DisplayName("Password")]
public string Password { get; set; }
[Required(ErrorMessage = "Email Id Required")]
[DisplayName("Email ID")]
[RegularExpression(#"^\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$",
ErrorMessage = "Email Format is wrong")]
public string Email { get; set; }
}
My database context is as below
public class ContextDB:DbContext
{
public DbSet<Login> LoginModel { get; set; }
}
The table created in the database is Logins.
In my view the validation messages are not working.
Can anyone please help?
This might sound stupid bud are u sure that you are passing right class to your Login ActionResult, not some LoginViewModel or similar stuff? I know that by default some preloaded models exist, so make sure that this isnt case.
Can the built in ASP MVC validation be made to behave differently for different actions of a same controller ? For example I have a user controller and it has actions like create, edit and other actions. So in model user the attribute Username is being validated for its uniqueness. If there is an user present with the same username, it throws and error username already present. So using the same validator for edit action throws an error "username already present" while editing an user. Can anybody tell me if there is a way to do solve this problem? I am pasting my validator code for reference.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace Models
{
[MetadataType(typeof(AdmiUserMetadata))]
public partial class AdminUser
{
public class AdmiUserMetadata
{
[Required(ErrorMessage = "Required Field")]
public string Id { get; set; }
[Required(ErrorMessage = "Required Field")]
[RegularExpression("[\\S]{6,}", ErrorMessage = "Must be at least 6 characters.")]
[Username(ErrorMessage = "Username already taken")]
public string Username { get; set; }
[Required(ErrorMessage = "Required Field")]
[RegularExpression("[\\S]{6,}", ErrorMessage = "Must be at least 6 characters.")]
public string Password { get; set; }
[Required(ErrorMessage = "Required Field")]
public string Name { get; set; }
[Required(ErrorMessage = "Required Field")]
[RegularExpression("^[a-z0-9_\\+-]+(\\.[a-z0-9_\\+-]+)*#[a-z0-9-]+(\\.[a-z0-9-]+)*\\.([a-z]{2,4})$", ErrorMessage ="Invalid E-mail ID")]
public string Email { get; set; }
[Required(ErrorMessage = "Required Field")]
[RegularExpression("(Active|Disabled)", ErrorMessage = "Select the status of User")]
public string Status { get; set; }
[Required(ErrorMessage = "Required Field")]
[RegularExpression("^[1-9]", ErrorMessage = "Select the group of User")]
public string Group { get; set; }
}
}
public class UsernameAttribute : ValidationAttribute
{
IUserRepository _repository = new UserRepository();
public override bool IsValid(object value)
{
if (value == null)
return true;
if (_repository.IsUsernamePresent((string)value))
{
return false;
}
return true;
}
}
}
What you are validating is a business rule.
No two users can have the same username.
I would have a User service that enforces this rule on creation/edit. Attributes are best suited for input validation. (eg Is the integer non-negative? A valid email address? etc)
I don't see how this can be done if a class has attributes that determines validation. This obviously works for most projects, but for me this is also not working out.
If you need to attach different sets of validation rules check out http://fluentvalidation.codeplex.com/. I tried it and liked it.
It doesn't handle client validation. I dropped that because I have ajax calls in most parts and that feels a bit like client validation.
I've been playing around data annotations in MVC2 and am curious if there is an annotation to compare 2 properties (ie. password, confirm password)?
If you are using ASP.Net MVC 3, you can use System.Web.Mvc.CompareAttribute
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
[Required]
[DataType(DataType.Password)]
[Compare("Password")]
public string PasswordConfirm { get; set; }
Here you go: http://www.dotnetguy.co.uk/post/2010/01/09/Property-Matching-With-Data-Annotations.aspx
Edit:
New link: http://www.dotnetguy.co.uk/post/2010/01/09/property-matching-with-data-annotations/
System.Web.Mvc.CompareAttribute has been deprecated.
I was able to modify to work like this:
[Required]
[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; }
There's not one built in, however, you can make your own. See this link, which shows the "PropertiesMustMatchAttribute" that does just what you're looking for.