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
Related
I am getting an error
Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
when trying to submit on a simple create page. Below is the controller code and model. I can not figure out what the issue is.
All fields except ID are nullable in SQL. I know that the issue is coming from the fields resolution and technician - if I put them on the create form (which they are not on it now as I do not want them filled out) the submit works fine Any ideas?
Thanks,
EB
Controller:
public ActionResult Create()
{
HelpDesk b1 = new HelpDesk();
return View(b1);
}
[HttpPost]
public ActionResult Create(HelpDesk model)
{
db.HelpDesks.Add(model);
db.SaveChanges();
return RedirectToAction("Index");
}
Model:
public int ID { get; set; }
[DisplayName("Requested By")]
public string RequestedBy { get; set; }
[Required(ErrorMessage = "Requested By Required.")]
public string Request { get; set; }
[Required(ErrorMessage = "Request Required.")]
public string Resolution { get; set; }
[DisplayName("Assigned To")]
public string Technician { get; set; }
public string Status { get; set; }
public string CreatedBy { get; set; }
public string ModfiedBy { get; set; }
public Nullable<System.DateTime> CreateDate { get; set; }
public Nullable<System.DateTime> ModifiedDate { get; set; }
All fields except ID is nullable in SQL.
That's not what you told Entity Framework, which is what's throwing the error. (And, as the error indicates, you should really check the EntityValidationErrors property on the exception, or an inner exception, for specific information about the error.) You told Entity Framework that these fields are required:
[Required(ErrorMessage = "Requested By Required.")]
public string Request { get; set; }
[Required(ErrorMessage = "Request Required.")]
public string Resolution { get; set; }
(It looks like you may have mixed up some of the property attributes, judging by the messages on them.)
I know that the issue is coming from the fields resolution and technician - if I put them on the create form (which they are not on it now as I do not want them filled out) the submit works fine
Sounds like that's the problem then. Resolution is marked as required, and you're not including it. Either include it or don't make it required.
I started working on my first serious MVC project for school unfortunately without defining the data annotations to the model first (so did not set "required" annotation, limit to size of attribute names etc.). I work with a viewmodel, and after adding the annotations the model is causing my ViewModel state to get invalid when posting the form.
It seems like it's the email required that is causing the issue. It is not used on viewmodel and in the form and it seems the viewmodel expects it will get it. Is there a way the form to stop demanding this field by setting some limitation in viewmodel (or controller). I would really prefer not to change the structure of the application (if I start from the scratch I would probably do this a bit different, but not much time is left to finalize the project)
Customer (Model)
public Class Customer(){
public int Id { get; set; }
[Required(ErrorMessage = "Required")]
[StringLength(25, ErrorMessage = "Message"]
public string Name { get; set; }
public string Logo { get; set; }
//[Required(ErrorMessage = "Email required")]
//[Display(Name = "E-mail")]
//[RegularExpression(xxxx, ErrorMessage = "not correct")]
public string Email { get; set; }
public int UserId { get; set; }
}
ViewModel
public class CustomerEditViewModel
{
public Customer Customer { get; set; }
[FileTypes("jpg,jpeg,png")]
[FileSize(1024 * 1024, ErrorMessage = "Max x bytes")]
public HttpPostedFileBase File { get; set; }
}
You can remove errors from the modelstate in your controller, e.g.
this.ModelState[key].Errors.Clear();
where key is the bit to be cleared, so if it's email it's most likely -
this.ModelState["Customer.Email"].Errors.Clear();
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 am developing MVC application using EF 4.0.
I am trying to put value , <test> to the address field but while saving its gives an below error , how to solve it ?
A potentially dangerous Request.Form value was detected from the client (Address="<test>").
Edit
Please check below code
namespace CEntities
{
[MetadataType(typeof(EmployeeMetaData))]
public partial class Employee
{
}
/// <summary>
/// Holds the validations for Employee class
/// </summary>
public class EmployeeMetaData
{
[Key]
public int Id { get; set; }
[Required]
[StringLength(50, ErrorMessage = "First name can accept maximum 50 characters.")]
public string FirstName { get; set; }
[StringLength(50, ErrorMessage = "Last name can accept maximum 50 characters.")]
public string LastName { get; set; }
[StringLength(1000, ErrorMessage = "Address can accept maximum 1000 characters.")]
public string Address { get; set; }
}
}
Please check below code
namespace CEntities
{
[MetadataType(typeof(EmployeeMetaData))]
public partial class Employee
{
}
/// <summary>
/// Holds the validations for Employee class
/// </summary>
public class EmployeeMetaData
{
[Key]
public int Id { get; set; }
[Required]
[StringLength(50, ErrorMessage = "First name can accept maximum 50 characters.")]
public string FirstName { get; set; }
[StringLength(50, ErrorMessage = "Last name can accept maximum 50 characters.")]
public string LastName { get; set; }
[StringLength(1000, ErrorMessage = "Address can accept maximum 1000 characters.")]
public string Address { get; set; }
}
}
You can use ValidateInput(false) to turn off Request Validation or you can add [AllowHtml] Attribute to your model property
Edited :
add [AllowHtml] attribute on Address model property.
[StringLength(1000, ErrorMessage = "Address can accept maximum 1000 characters.")]
[AllowHtml]
public string Address { get; set; }
and add using System.Web.Mvc; directive on top.
Are you using Assembly System.Web.Mvc.dll, version 4 or version 2.
[AllowHtml] attribute is in Assembly System.Web.Mvc.dll, version 4. check your assembly version to apply this.
#YograjGupta gave you a good answer, I'm not sure why [AllowHtml] is not working. Another option is in the controller, were you save the EmployeeMetaData to the database, you can add db.Configuration.ValidateOnSaveEnabled = false;, before you save changes. You will also have to remove the if(ModelState.IsValid) part.
Another option would be to replace the < and > with employeeMetaData.Address.Replace("<", "<").Replace(">", ">")
Keep in mind that if you use the [AllowHtml] attribute, it makes you more vulnerable to hacking, so you may want to remove it before your final release. Or you can add Microsoft.Security.Application and do something like Sanitizer.GetSafeHtmlFragment(address) to remove unsafe html.
Edit
Your controller should look something like this:
public ActionResult Create(Employee employee)
{
employee.Address = employee.Address.Replace("<", "<").Replace(">", ">");
if(ModelState.IsValid)
{
db.Employees.Add(employee);
db.SaveChanges();
return RedirectToAction("Index");
}
}
Or you could try this:
public ActionResult Create(Employee employee)
{
db.Configuration.ValidateOnSaveEnabled = false;
db.Employees.Add(employee);
db.SaveChanges();
return RedirectToAction("Index");
}
db is your database and Employee is the Employee table in your database.
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.