I want to display two different error message. First give for required and second for Int64 value. Here is my code.
[Display(Name = "Employee")]
[Required]
public Int64 EmployeeId { get; set; }
You can use the RangeAttribute.
[Required(ErrorMessage = "Msg1")]
[Range(10, 1000,
ErrorMessage = "Value for {0} must be between {1} and {2}.")]
public object Weight;
You can use data annotation extentions here: http://dataannotationsextensions.org/
Then add the two annotations as follows:
[Required(ErrorMessage = "Employee Id is required")]
[DataAnnotationsExtensions.Integer(ErrorMessage = "Please enter a valid number.")]
public Int64 EmployeeId { get; set; }
Related
I have the following model:
public class Human
{
[Required]
[StringLength(50)]
[Display(Name = "First Name")]
public String FirstName { get; set; }
[Required]
[StringLength(50)]
[Display(Name = "Last Name")]
public String LastName { get; set; }
// 50 more required fields not shown for brevity
}
If a user doesn't fill out a required field, I would like the error message to be "This field is required". However, I don't want to annotate every single one with [Required(ErrorMessage = "This field is required")] because that takes a lot of copy/pasting.
Is there a way to tell ASP.NET MVC that all required fields in ONLY THIS CLASS should have the error message "This field is required"?
I did not find a way to accomplish this. I think it is not possible.
I'm using ASP.NET MVC with EF code first.
In my model I have a property that can be null:
public byte[] Avatar { get; set; }
However, when I run update-database I get:
Cannot insert the value NULL into column 'Avatar', table 'temp';
column does not allow nulls. UPDATE fails.
I don't have a dataannotation specifying the property to be required, nor is the property a foreign key.
Any ideas?
Further updates:
If I delete my database and force a new one to be created with 'update-database -verbose' then I can see the table being created specifically forces a NOT NULL flag on my field:
CREATE TABLE [dbo].[UserProfile] (
[UserId] [int] NOT NULL IDENTITY,
[UserName] [nvarchar](max),
[FirstName] [nvarchar](50) NOT NULL,
[LastName] [nvarchar](50) NOT NULL,
[EmailAddress] [nvarchar](50) NOT NULL,
[WorkPhone] [nvarchar](20),
[MobilePhone] [nvarchar](20),
[HireDate] [datetime],
[Avatar] [image] NOT NULL,
[AvatarMimeType] [nvarchar](max),
CONSTRAINT [PK_dbo.UserProfile] PRIMARY KEY ([UserId])
)
My full model:
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
[Required]
[Display(Name = "First name")]
[MaxLength(50, ErrorMessage = "First Name cannot be longer than 50 characters.")]
public string FirstName { get; set; }
[Required]
[Display(Name = "Last Name")]
[MaxLength(50, ErrorMessage = "Last Name cannot be longer than 50 characters.")]
public string LastName { get; set; }
[Display(Name = "Full Name")]
public string FullName
{
get
{
return FirstName + " " + LastName;
}
}
[Required]
[RegularExpression("^[a-z0-9_\\+-]+(\\.[a-z0-9_\\+-]+)*#[a-z0-9]+(\\.[a-z0-9]+)*\\.([a-z]{2,4})$", ErrorMessage = "Not a valid email address")]
[Display(Name = "Email Address")]
[MaxLength(50, ErrorMessage = "Email Address cannot be longer than 50 characters.")]
public string EmailAddress { get; set; }
[Display(Name = "Work Phone")]
[MaxLength(20, ErrorMessage = "Work Phone cannot be longer than 20 characters.")]
public string WorkPhone { get; set; }
[Display(Name = "Mobile Phone")]
[MaxLength(20, ErrorMessage = "Mobile Phone cannot be longer than 20 characters.")]
public string MobilePhone { get; set; }
[Display(Name = "Hire Date")]
[DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? HireDate { get; set; }
[ValidateFile(ErrorMessage = "Please select a PNG, JPG or GIF image smaller than 2MB")]
[Column(TypeName = "image")]
public byte[] Avatar { get; set; }
public string AvatarMimeType { get; set; }
[Column(TypeName = "image")]
public byte[] Avatar { get; set; }
I think you need to tell EF that you are using it in this fashion. Try using the image annotation as above.
This will make sure your field is created as the image type; designed for this type of scenario.
EDIT: Please see the comments for the answer that eventually worked.
Change it from byte[] to byte?[]
It isn't maybe direct answer but useful workaround. When you are creating entity,initalize Avatar field:
public void CreateSomething(Something something)
{
something.Avatar= new byte[0],
Db.Somethings.Add(something);
Db.SaveChanges();
}
For EF Avatar now is not null so everything is ok.
Hope,it will help.
Try the solution noted here: What is the data annotation for changing nullable and not null data types?
I.E:
Change it from byte[] to byte?
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
I have a class, employee, in which the user inputs values for the properties on one screen, and then some more on another screen.
The problem I have with this is how to validate these properties?
If I put validation attributes for the properties of the class I have a problem. The validation takes place whether the field is displayed on the form or not.
So for my Employee class I have had to comment out some of the validation in order to get it to work on 1 screen. It probably won't work on the other.
private sealed class Metadata
{
[HiddenInput(DisplayValue=false)]
public int EmployeeId { get; set; }
[DisplayName("Forename")]
[DataType(DataType.Text)]
[Required(ErrorMessage = "Forename is required")]
public string Forename { get; set; }
[DisplayName("Surname")]
[DataType(DataType.Text)]
[Required(ErrorMessage = "Surname is required")]
public string Surname { get; set; }
[DisplayName("Middle Names")]
[DataType(DataType.Text)]
public string Middlenames { get; set; }
//[DisplayName("User Name")]
//[DataType(DataType.Text)]
//[Required(ErrorMessage = "User name is required")]
//public string UserName { get; set; }
[DisplayName("Employee Number")]
[DataType(DataType.Text)]
[Required(ErrorMessage = "EmployeeNumber is required")]
public string EmployeeNumber { get; set; }
[DisplayName("Department")]
[UIHint("DropDownList")]
[Required(ErrorMessage = "You must select a department from a division")]
public int DepartmentId { get; set; }
[DisplayName("User Role")]
[UIHint("DropDownList")]
[Required(ErrorMessage = "You must select a role")]
public int SHP_UserRoleId { get; set; }
//[DisplayName("Email")]
//[DataType(DataType.EmailAddress)]
//[Required(ErrorMessage = "Email is required")]
//[RegularExpression(#"^[\w-\.]+#([\w-]+\.)+[\w-]{2,4}$", ErrorMessage = "Not a valid email")]
//[UniqueEmail(ErrorMessage = "User already exists")]
//public string EmailAddress { get; set; }
[DisplayName("End Date")]
public DateTime? EndDate { get; set; }
}
That's a common problem people encounter when they try to use their business models in the views and the reason for this is that business models are closer to the business and the view is closer to the application (it's just a representation of this business model). Today you have two screens, tomorrow maybe three.
For this reason I would recommend you using view models which reflect a given view. So in your case you could have two view models for each view and populate them from the same business model. Validation attributes could be placed on view models. To avoid boilerplate code in converting between your business models and your view models you could use AutoMapper.
The article here mentions the use of Data Annotations Model Binder that is available here.
Does anyone know what it's intent is? To do DA validation, I don't need a special Model binder in MVC 2.0
The first release of ASP.Net MVC didn't support validation via Data Annotations as part of the framework. The intent of the linked codeplex code was to specifically allow usage of attribute oriented validation (which was in high demand) as a stopgap to the solution that was implemented in the second release.
DataType
Specify the datatype of a property
DisplayName
specify the display name for a property.
DisplayFormat
specify the display format for a property like different format for Date proerty.
Required
Specify a property as required.
ReqularExpression
validate the value of a property by specified regular expression pattern.
Range
validate the value of a property with in a specified range of values.
StringLength
specify min and max length for a string property.
MaxLength
specify max length for a string property.
Bind
specify fields to include or exclude when adding parameter or form values to model properties.
ScaffoldColumn
specify fields for hiding from editor forms.
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
namespace Employee.Models
{
[Bind(Exclude = "EmpId")]
public class Employee
{
[ScaffoldColumn(false)]
public int EmpId { get; set; }
[DisplayName("Employee Name")]
[Required(ErrorMessage = "Employee Name is required")]
[StringLength(100,MinimumLength=3)]
public String EmpName { get; set; }
[Required(ErrorMessage = "Employee Address is required")]
[StringLength(300)]
public string Address { get; set; }
[Required(ErrorMessage = "Salary is required")]
[Range(3000, 10000000,ErrorMessage = "Salary must be between 3000 and 10000000")]
public int Salary{ get; set; }
[Required(ErrorMessage = "Please enter your email address")]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email address")]
[MaxLength(50)]
[RegularExpression(#"[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}", ErrorMessage = "Please enter correct email")]
public string Email { get; set; }
}
}