In an ASP.NET MVC 4 app, the LocalPasswordModel class (in Models\AccountModels.cs) looks like this:
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; }
}
The above code contains two substitution arguments in the ErrorMessage string:
ErrorMessage = "The {0} must be at least {2} characters long."
Can someone tell me where the values that get substituted into that string come from? More generally, is there anything approximating official documentation that describes how parameter substitution works in this context?
For StringLengthAttribute, the message string can take 3 arguments:
{0} Property name
{1} Maximum length
{2} Minimum length
These parameters unfortunately do not seem to be well documented. The values are passed in from each validation attribute's FormatErrorMessage attribute. For example, using .NET Reflector, here is that method from StringLengthAttribute:
public override string FormatErrorMessage(string name)
{
EnsureLegalLengths();
string format = ((this.MinimumLength != 0) && !base.CustomErrorMessageSet) ? DataAnnotationsResources.StringLengthAttribute_ValidationErrorIncludingMinimum : base.ErrorMessageString;
return String.Format(CultureInfo.CurrentCulture, format, new object[] { name, MaximumLength, MinimumLength });
}
It is safe to assume that this will never change because that would break just about every app that uses it.
Related
I have created a new MVC project (default MVC5 Individual User Accounts template) and I have made changes to IdenitityConfig.cs
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 1,
RequireNonLetterOrDigit = false,
RequireDigit = false,
RequireLowercase = false,
RequireUppercase = false,
};
But still while registration it gives an error "The Password must be at least 6 characters long."
But I have changed length to 1.
Its not passing the viewmodel validation.
public class RegisterViewModel
{
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { 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; }
}
If you remove this line [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)], you will not have this issue.
I'm developing a MVC project, I want to validate it for some text filed are uppercase. How can I do it?
I'm using this **text-transform:uppercase** but I want to validate in model
[DisplayName("Last Name :")]
[Required]
[StringLength(50, MinimumLength = 3, ErrorMessage = "Last Name must be between 3 and 50 characters!")]
public string LastName { get; set; }
[RegularExpression(#"[A-Z]{3,50}$",
ErrorMessage = "Only uppercase Characters are allowed.")]
use regular expression attribute.
Is there a way using data annotation to compare two model properties and report error if they are the same? I know the way using Compare to report error if different but how to do it the opposite way?
For example, the code below is direct copy from the MVC RegisterModel class
[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; }
In the above code, the validation will fail if the Password and ConfirmPassword are different. What I want is the opposite, I want to report the error if the Password and ConfirmPassword are the same.
I know I can create my own ValidationAttribute but just wondering if there's one already built-in for validate the opposite.
For this you can use CustomValidation
Decorate your Entity class with an attribute like this:
[CustomValidation(typeof(MyEntity), "ArePropertiesEqual")]
Public class MyEntity
{
public string prop1 { get; set; }
public string prop1 { get; set; }
}
And implement a function called: ArePropertiesEqual like this:
public static ValidationResult ArePropertiesEqual(MyEntity myEntity, ValidationContext validationContext)
{
if(myEntity.prop1 != myEntity.prop2)
return new ValidationResult("propertiesdont match", new[] { "prop1", "prop2" });
return ValidationResult.Success;
}
I'm using Identity, and the IdentityUsers properties are the next: https://msdn.microsoft.com/en-us/library/microsoft.aspnet.identity.entityframework.identityuser_properties%28v=vs.108%29.aspx
Well, the problem is I have in the AspNetUsers table "Email" and "PasswordHash", but appears the error'System.ComponentModel.DataAnnotations.DataType' does not contain a definition for 'Email' and 'PasswordHash')
if I put "Datatype.Email" instead of "DataType.EmailAddress" and "DataType.PasswordHash" instead of "DataTtype.Password".
public class RegisterViewModel
{
[Required]
[DataType(DataType.Email)]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The password must have at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.PasswordHash)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.PasswordHash)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "Different passwords.")]
public string ConfirmPassword { get; set; }
}
The error is telling you exactly what you need. DataType is an enumeration which only allows specific values. These in turn are used for validation in the MVC world to ensure that you have a valid EmailAddress in the field, whatever it happens to be called.
[DataType(DataType.Email)] // Not Valid
[DataType(DataType.EmailAddress)] // Valid
[DataType(DataType.PasswordHash)] // Not Valid
[DataType(DataType.Password)] // Valid
For the full list of valid values, see Intellisense or this URL:
https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.datatype%28v=vs.110%29.aspx
I have two models i.e. Login and Register:
Login Model
public class LoginModel
{
[Required(ErrorMessage = "Email is required")]
[RegularExpression("^[a-z0-9_\\+-]+(\\.[a-z0-9_\\+-]+)*#[a-z0-9-]+(\\.[a-z0-9-]+)*\\.([a-z]{2,4})$", ErrorMessage = "Not a valid email")]
[DataType(DataType.EmailAddress)]
[DisplayName("Email")]
[StringLength(150, ErrorMessage = "Must be less than 150 characters")]
public string Email { get; set; }
[Required(ErrorMessage = "Password is required")]
[DataType(DataType.Password)]
[DisplayName("Password")]
[StringLength(30, ErrorMessage = "Must be less than 30 characters")]
public string LoginPassword { get; set; }
[DisplayName("Remember me")]
public bool Remember { get; set; }
}
Register Model:
public class RegisterModel
{
[Required(ErrorMessage = "Email is required")]
[RegularExpression("^[a-z0-9_\\+-]+(\\.[a-z0-9_\\+-]+)*#[a-z0-9-]+(\\.[a-z0-9-]+)*\\.([a-z]{2,4})$", ErrorMessage = "Not a valid email")]
[DataType(DataType.EmailAddress)]
[DisplayName("Email")]
[StringLength(150, ErrorMessage = "Must be less than 150 characters")]
public string Email { get; set; }
[Required(ErrorMessage = "Full Name is required")]
[DisplayName("Full Name")]
[StringLength(50, ErrorMessage = "Must be less than 50 characters")]
public string FullName { get; set; }
[Required(ErrorMessage = "Password is required")]
[DataType(DataType.Password)]
[DisplayName("Password")]
[StringLength(30, ErrorMessage = "Must be less than 30 characters")]
public string RegisterPassword { get; set; }
[Required(ErrorMessage = "Confirm Password is required")]
[DataType(DataType.Password)]
[DisplayName("Confirm Password")]
[StringLength(30, ErrorMessage = "Must be less than 30 characters")]
public string ConfirmPassword { get; set; }
[Required(ErrorMessage = "Please read and agree the terms and condition.")]
[DisplayName("I agree to the terms and conditions")]
public bool AgreeTerms { get; set; }
}
And they both are called on the home page using a seperate modal popups --> so lets say if a user register himself (and while registering he presses enter without entering email and validation message is displayed). After successfully registering, user tries to login (and he again presses the enter without entering email) but this time the validation message is not displayed.
As per my knowledge, the reason for not showing the validation summary is that the validation message is appearing in the register modal which is not visible at the moment and it is because both models uses an email (named : Email) field attribute.
I can achieve my desire behaviour using different name for email field, but is there any way without doing this ???
And addition to this can I inherit from Register model and use it for login purpose also, while doing this what will be the output of my above scenario?
You'd have to modify the editor templates to include a prefix or something making them unique. Here's an answer that provides some extension methods that I think would work TextBoxFor rendering to HTML with prefix on the ID attribute .