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.
Related
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.
I've installed yesterday Visual Studio 2012 (RTM, via mytt DreamSpark account) and created a demo MVC site (using .NET 4.0 since I wish it to be supported on Azure).
I've started to investigate the project and in addition to built-in option to use external services (Facebook, Twitter, Windows Live and Google) I've found out that the entire membership schema has been changed:
The new structure contains 4 tables (the UserProfile is a first-code approch Entity Framework table).
Note that although the tables prefix is "webpages_" its a proper MVC 4 site.
I've opened the AccountModels.cs file and saw that it has been changed too:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Globalization;
using System.Web.Mvc;
using System.Web.Security;
namespace MyGuestbook.Models
{
public class UsersContext : DbContext
{
public UsersContext()
: base("DefaultConnection")
{
}
public DbSet<UserProfile> UserProfiles { get; set; }
}
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
}
public class RegisterExternalLoginModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
public string ExternalLoginData { get; set; }
}
public class LocalPasswordModel
{
[Required]
[DataType(DataType.Password)]
[Display(Name = "Current password")]
public string OldPassword { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm new password")]
[Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public class LoginModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
public class RegisterModel
{
[Required]
[Display(Name = "User name")]
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")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public class ExternalLogin
{
public string Provider { get; set; }
public string ProviderDisplayName { get; set; }
public string ProviderUserId { get; set; }
}
}
So I would like to ask:
- Does this the new users structure (that is generated from asp_regsql.exe) or this is a template-specific structure?
- Does somebody have any documentation about the new structure and how to integrate with it?
- Does anybody know how one can migrate an "older" project (e.g. MVC 3 project) with the old structure to the new one?
Thanks! :)
I've found some article that answer my question.
Edit:
Why the sudden changes:
The changes has been made because Microsoft has changed the default ASP.NET MVC 4 template.
The standard "Internet Application" template which gives default accounts management has been changed and now using the WebMatrix 2 helpers.
The AccountController has been totally rewritten in order to use SimpleMembership class which supports the third-party integration and gives us the ability to use Entity Framework code-first approach.
Usage of old membership providers
As long as I've read, because the SimpleMembership class using ExtendedMembershipProvider you cannot use the default universal providers and must use the built-in provider OR creating an ExtendedMembershipProvider custom provider.
More information can be found here:
Implementing membership providers using the new ASP.NET WebForms and ASP.NET MVC 4 template
Cheers!
For the edition of my user, I've to ensure that password and the repeat password are the same. I found the "Compare" validator, but I cant make it work.
my model looks like the following:
public class UserEditionViewModel{
[Compare("User.Password")]
public String RepeatPassword{get;set;}
public User User {get;set;}
public List<Language> AvailableLanguages{get;set;}
public List<Country> AvailableCountries{get;set;}
}
and the User model:
public class User{
[Required]
public String Name{get;set;}
//lot of other properties omitted...
[RegularExpression(#"(|.*(?=.{6,})(?=.*\d)(?=.*[a-zA-Z]).*)", ErrorMessageResourceType = typeof(LocalizationResources.Views.User.Edition), ErrorMessageResourceName = "InvalidPassword")]
//And I've localization attributes
public String Password{get;set;}
}
In the view I only have something like:
#Html.PasswordFor(m=>m.User.Password)
#Html.PasswordFor(m=>m.RepeatPassword)
But I ever get this error, even if the two items are matching:
'Password repeat' and 'User.Password' do not match.
I also got this error when I'm doing the client validation.
For me the most obvious error is that it can't found the subproperty. Am I right? If yes, how to avoid this behavior. If no, what can be the problem???
A workaround would be to create another property on the UserEditionViewModel that reads and writes to the inner Userclass.
public String UserPassword
{
get
{
return User.Password;
}
set
{
User.Password = value;
}
}
And then bind your controls to that property instead, and change the [Compare("User.Password")] to [Compare("UserPassword")]. I'm not really sure if it can be done any other way short of writing your own custom validator.
I had a similar problem and ended up writing my own validator for this which turned out surprisingly complex since you can have any layer of inheritance to get to your property. If there is another solution, I'd be equally happy to know about it.
You can try this which worked for me..
In your project -> References-> right click->Manage NuGet Packages..
install DataAnnotationsExtensions package.
Then validate your model as follows:
public class Employee
{
[Required(ErrorMessage="Name field Required")]
public string name { get; set; }
[Required(ErrorMessage = "Name field Required")]
public string email { get; set; }
[Required(ErrorMessage = "Depatrment field Required")]
public string department { get; set; }
[Required(ErrorMessage = "Designation field Required")]
public string designation { get; set; }
public string phone { get; set; }
[Required(ErrorMessage = "Password field Required")]
[Display(Name="Password")]
public string password { get; set; }
[Required(ErrorMessage="Confirm password")]
[Display(Name="Re-type Password")]
[EqualToAttribute("password",ErrorMessage="Password miss-match")]
public string Re_Password { get; set; }
}
That's it
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; }