Prevent user from submitting default form values in .NET MVC3 - asp.net

I have the following model:
public class Contact
{
public Contact()
{
Name = "Your Name";
Email = "Your Email";
Message = "Your Message";
}
[Required]
[StringLength(60,MinimumLength = 3)]
public string Name { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[RegularExpression(#"\b[A-Z0-9._%-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b")]
public string Email { get; set; }
[Required]
[StringLength(2200, MinimumLength = 10)]
[DataType(DataType.MultilineText)]
public string Message { get; set; }
}
For Message and Name, their default values (in the constructor) actually pass validation, obviously that is bad. I know I could check for this and throw an error in the Controller, but I'm trying to find a way to do these in the model (as I assume that is the correct place to do it).

I wouldn't do this at all server side. Use a textbox watermark ala one of the many methods for ex.
http://code.google.com/p/jquery-watermark/

Those look like hints, not default values. You should implement these with javascript, instead of setting them as input values.

Related

Return empty error message in validation

I want to return empty string for my validation in ASP.NET MVC 5 project. I have created a property in my view model:
[Required(ErrorMessageResourceType = typeof(TestResources), ErrorMessageResourceName = "Empty_Message", ErrorMessage = null)]
public int? TestProperty { get; set; }
Inside a view:
#Html.ValidationMessageFor(x => x.TestProperty)
When I try this one I get the default message "This field is required.". I want it to be empty in this case, because I add a class to error message's span element that shows up some icon.
I tried something like that:
[Required(ErrorMessage = "")]
public int? TestProperty { get; set; }
...but got an error:
Either ErrorMessageString or ErrorMessageResourceName must be set, but
not both.
Try setting a space. Example "Space". That would solve your problem.
[Required(ErrorMessage = " ")]
public int? TestProperty { get; set; }
you can use the following code:
[DisplayFormat(ConvertEmptyStringToNull=false)]
Reference for more details:
RequiredAttribute with AllowEmptyString=true in ASP.NET MVC 3 unobtrusive validation

Asp.Net MVC Validations Not working

[Display(Name = "SentDoc_lblDescription ", ResourceType = typeof(EXTDocuments.Resources))]
[Required(ErrorMessage="Description Required")]
public string Description {get;set;}
This Description Property is required in business logic.
When I am clicking submit button it throws an error.
The error is decription is null, I want to validate that property from within the UI.
I want to recall running into something like this and currently use this attribute set in order to ensure my strings get validated correctly:
[Required]
[MaxLength(200)]
[MinLength(5)]
[Display(Name = "Name")]
public string ItemName { get; set; }
By using the MinLength and Required, you get a required string with a minimum length. Hopefully this helps you out.

MVC models' unique field Create-Edit Complication

I have a model in MVC like that;
public class Employee
{
public int EmployeeId { get; set; }
[Required]
[EmailAddress]
[DisplayName("Email")]
[Remote("doesEmailExist", "Employee", HttpMethod = "POST", ErrorMessage = "Email already exists. Please enter a different Email.")]
public string Email { get; set; }
}
On create action, that is okey, it works great. But on edit action, program see email address already exist. And I cannot update my employee with the same email address. What can I do?
You could use the AdditionalFields property of RemoteAttribute to include EmployeeId in the validation. Then in your action method, if EmployeeId=null validation fails if a matching email is found, otherwise only check for matching emails where its a different EmployeeID

ASP.NET MVC 3 Model Validation

I have a model called Organisation, on the organisation I have a remote validation attribute:
[Required(ErrorMessage = "The organisation name is required")]
[Remote("NameCheck", "Manage", "Organisations", ErrorMessage="That organisation already exists")]
public string Name { get; set; }
This checks that the name of the organisation someone is adding doesn't already exists. If it does then they get an error message saying so.
I'm using a strongly typed view to render the organisation "edit" view. Because someone is editing, I don't want that remote validation to run because of course the organisation will exist.
Is there any way to achieve this? Basically, turn off the remote validation in some way when editing an organisation and have it turned on when creating an organisation.
You could/SHOULD use different view models for the two views. So for example you will have CreateOrganizationViewModel and UpdateOrganizationViewModel. On the first view model the Name property will be decorated with the remote attribute whereas on the second view model it will not.
public class BaseOrganizationModel {
public int ID {get; set;}
}
public class UpdateOrganizationModel : BaseOrganizationModel {
[Required(ErrorMessage = "The organisation name is required")]
public string Name { get; set; }
}
public class InsertOrganizationModel : BaseOrganizationModel {
[Required(ErrorMessage = "The organisation name is required")]
[Remote("NameCheck", "Manage", "Organisations", ErrorMessage="That organisation already exists")]
public string Name { get; set; }
}

ASP.Net MVC3 conditional validation

I'm having some troubles with validation on my application.
Let's say I've the following models:
public class Company
{
public int id { get; set; }
[Required]
public String Name { get; set; }
public String Location { get; set; }
public List<Contacts> Contacts { get; set; }
}
public class Contact
{
public int id { get; set; }
[Required]
public String Name { get; set; }
[DataType(DataType.EmailAddress)]
public String Email { get; set; }
public String Telephone { get; set; }
public String Mobile { get; set; }
}
Now in my company create view I've two buttons, one to add contacts to the company, and another one to create the new company.
I detected which button was used in my controller like this (both buttons are named "button"):
[HttpPost]
public ActionResult Create(String button, FormCollection collection)
{
if(button == "AddContact")
{
AddContact(collection);
}
else
{
CreateCompany(collection);
}
}
While it's being created the object that represents the company that it's being create is stored in the session (for example HttpContext.Session["company"] = company;)
Now the problem is that if, for example, I try to add a contact without first specifying the company name, i get a validation error because the company name is required, which shouldn't happen because the user might want to add the contacts before adding the company info. Or if I try to save the company, I also get a validation error, because usually when saving the "add contact" form is empty, which means that the contact name (which is required as well) was not specified.
What I want to know is that if it's possible to validate the contact properties only when the addContact button is used, and validate the company properties only when the createCompany button is pressed.
For now i only need to do this serve-side, but if anyone has a solution to do this client-side as well i would appreciate the help.
You could trigger your own validation on the individual objects using
Validator.TryValidateObject(Object, ValidationContext, ICollection)
You can provide conditional validation using the Entity Framework by overriding DbEntityValidationResult in the DbContext. When this validation occurs in the DbContext you can access other entities. When validating a contact you can check the company too. For example:
protected override DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry, IDictionary<object, object> items)
{
var result = base.ValidateEntity(entityEntry, items);
ValidateContact(result);
return result;
}
private void ValidateContact(DbEntityValidationResult result)
{
var contact= result.Entry.Entity as Contact;
if (contact!= null && contact.ContactId != 0)
{
// Add validation code here, such as:
if(!string.IsNullOrEmpty(contact.Company.Name){
result.ValidationErrors.Add(
new DbValidationError(
"Contact",
"Company name cannot be null or empty when validating contacts.")
);
}
}
}
See Julia Lerman's Programming Entity Framework: DbContext http://www.amazon.com/Programming-Entity-Framework-Julia-Lerman/dp/1449312969 for more details.

Resources