In my model I've got a non-nullable DateTime field. I haven't made it a required field. When I leave the corresponding input in the view empty and check for the modelstate I see that the validation fails on this field. It says "Value cannot be empty". Now, I understand that simple values can't be null so they have to be assigned some value. I also understand that making this field nullable will solve the problem. But how can I catch the case when the attempted value is empty for a certain field (just like default model binding does) to show my custom error message instead of the generic one?
public class Person
{
[DataType(DataType.DateTime)]
[Required(ErrorMessage = 'show my custom error message instead of the generic one')]
public DateTime StartDate{get;set;}
}
explicitly specify error messages as strings. Alternatively you can define them within resource files and optionally localize them depending on the language/culture of the incoming user.
Related
I am trying to replace the default validation messages in MVC3 that are displayed when you fail to fill in a required field or fill in an invalid value. I am only addressing server-side validation in this question. My custom message for invalid value is working, but the one for missing required field won't apply.
This is what I have done:
Added an ASP.NET folder called "App_GlobalResources" to the web project, and in that folder I placed a resources file called "DefaultMessages.resx", containing the following keys and values:
PropertyValueInvalid: The value you input is invalid
PropertyValueRequired: This field is required
(These are not the actual messages I will be using; they will be in a different language, which is my primary reason for needing to replace the default ones.)
Registered the resource file with the DefaultModelBinder in Global.asax.cs like this (note I am using Ninject for dependency injection):
public class MvcApplication : NinjectHttpApplication
{
...
protected override void OnApplicationStarted()
{
...
DefaultModelBinder.ResourceClassKey = "DefaultMessages";
...
}
...
}
In my model I have a DateTime property called ExpirationDate. Since DateTime is non-nullable, the property is implicitly required. PropertyValueInvalid works; my custom message is rendered in the form after I submit with an invalid value in the ExpirationDate field, such as 30.02.2014. But if I leave the field empty and submit, I only get the default "The ExpirationDate field is required".
What am I missing here? Is PropertyValueRequired not the right name? Or does it not apply to implicitly required properties? I also tried adding an explicit Required attribute in the Model, like this:
[Required]
public DateTime ExpirationDate{ get; set; }
But that makes no difference. What does work is adding a custom error message to the attribute, for example like this:
[Required(ErrorMessage = "We need a date here!")]
public DateTime ExpirationDate{ get; set; }
But I don't want to do that for all the required properties that typically just need a generic message. (I know I could reference the generic message in the resource file in the Required attribute instead of stating the message directly, but that still adds clutter to the Model that should not be necessary.)
For the date validation you need to handle the localization of : FieldMustBeDate actually what you are doing is correct but in order to handle all messages you need to have the following messages localized just in case:
FieldMustBeDate
FieldMustBeNumeric
PropertyValueInvalid
PropertyValueRequired
How to validate that user enters string in textbox in asp mvc4?
What to write in required tag?
[required]
Use the [RegularExpression] attribute if you want to limit the user to only typing in alphabetic characters.
More info on MSDN.
Here is a good link to a regular expression that you can use.
This example maybe helps:
public class CustomerMetaData
{
// Require that the Title is not null.
// Use custom validation error.
[Required(ErrorMessage = "Title is required.")]
public object Title;
// Require that the MiddleName is not null.
// Use standard validation error.
[Required()]
public object MiddleName;
}
There are many ways to do it
1) By using plain Javascript or JQuery to check if it has value before submiting the page
2) On controller method check if it has value
3) If you a using EF and your view binded to a model add attribute called [Required]to the property of that model.
What do you actually want to do?
Make sure that the object the server receives has correct data in it? Then you should use data attributes on your C# model. However what do you mean by "enters string"? If the user simply needs to enter any string, then [Required] works - this just means that there has to be some value entered. Do you only want to allow a specific set of characters, like the English alphabet? Then you need to use a RegularExpression attribute.
If you further specify what you actually want to do I am sure we can help you more.
In my view model I have this very simple member,
[RegularExpression(#"^[0-9\.]*$",
ErrorMessage = "The only value you can enter here is a number")]
public double salary{ get; set; }
but when I put a value like 'abc' into the textbox, I receive this error message,
The value 'abc' is not valid for salary.
which is not the error message I've defined. Is there some sort of default behavior that you can't overwrite with annotations? Do I have to write a custom validator?
Before the field is validated against your regular expression, it is being validated to ensure that it is the correct type. Since 'abc' can't be converted to a double, you get that error message.
You could make salary a string and then parse it into a double in your controller, that will prevent the conversion and allow your Regex error message to be displayed when an invalid value is entered.
Otherwise, use Html.ValidationMessageFor to override the validation message
#Html.ValidationMessageFor(m => m.salary, "The only value you can enter here is a number")
RegularExpression should be used for string type, it will not be called for a double type since it is not possible to assign 'abc' to a double in the first place.
I am trying to realize valition on data type. I have used DataAnnotations, but for data type it's not showing customized message
for example when I' am trying enter string data into int typed field. How I can customize messages in this case?
If I had to guess, you sound like you want a custom message to display when validating one or more fields in your model. You can subclass the DataAnnotations.ValidationAttribute class and override the IsValid(object) method and finally setting a custom ErrorMessage value (where ErrorMessage already belongs to the ValidationAttribute class)
public class SuperDuperValidator : ValidationAttribute
{
public override bool IsValid(object value)
{
bool valid = false;
// do your validation logic here
return valid;
}
}
Finally, decorate your model property with the attribute
public class MyClass
{
[SuperDuperValidator(ErrorMessage="Something is wrong with MyInt")]
public int MyInt { get; set; }
}
If you're using out-of-the-box MVC3, this should be all you need to propertly validate a model (though your model will probably differ/have more properties, etc) So, in your [HttpPost] controller action, MVC will automagically bind MyClass and you will be able to use ModelState.IsValid to determine whether or not the posted data is, in fact, valid.
Pavel,
The DataAnnotations DataType attribute does not affect validation. It's used to decide how your input is rendered. In such a case, David's solution above works.
However, if you want to use only the built-in validation attributes, you probably need to use the Range attribute like this:
[Range(0, 10, ErrorMessage="Please enter a number between 0 and 10")]
public int MyInt { get ; set ;}
(Of course, you should really be using the ErrorMessageResourceName/Type parameters and extract out hard-coded error message strings into resx files.)
Make sure to let MVC know where to render your error message:
<%= Html.ValidationMessageFor(m => m.MyInt) %>
Or you can just use EditorForModel and it will set it up correctly.
I don't think this has been answered because I have the same issue.
If you have a Model with a property of type int and the user types in a string of "asd" then the MVC3 framework binding/validation steps in and results in your view displaying "The value 'asd' is not valid for <model property name or DisplayName here>".
To me the poster is asking can this message that the MVC3 framework is outputting be customized?
I'd like to know too. Whilst the message is not too bad if you label your field something that easily indicates an number is expected you might still want to include additional reasons so it says something like:
"The value 'asd' is not valid for <fieldname>; must be a positive whole number."
So that the user is not entering value after value and getting different error messages each time.
I'm trying to get server-side validation of an Entity Framework String Property to work. Other server-side validation such as data type validation and required dateTime and numeric EF properties are working.
This in VS 2010, .Net 4.0, MVC2 + Cloud, ADO.Net Entity Framework.
The String Property I am having issues with is mapped to a SQL 2008, Varchar(50) non-nullable column.
When I try to post to my Create action with an empty string for this Property, I get the follwing error.
Exception Details: System.Data.ConstraintException: This property cannot be set to a null value.
When I post to the action with a blank space, I successfully get a required field validation message.
I have tried using Data Annotations and ClientSideValidation but there seems to be issues with ClientSideValidation working on partial views and jquery dialogs.
Here is the orginal autogenerated code from the entity framework.
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.String GradeTypeName
{
get
{
return GradeTypeName;
}
set
{
OnGradeTypeNameChanging(value);
ReportPropertyChanging("GradeTypeName");
_GradeTypeName = StructuralObject.SetValidValue(value, false);
ReportPropertyChanged("GradeTypeName");
OnGradeTypeNameChanged();
}
}
Depending on the signature of the Action method (CREATE or EDIT), the exception can occur before stepping into the method or within the method when UpdateModel() is called. The inner exception is at the line below from the model.designer.cs file.
_GradeTypeName = StructuralObject.SetValidValue(value, false);
I have been able to reproduce this on a simple mvc2 web application.
i was having the same problem for a while. I have found a piece of explanation here: http://mvcmusicstore.codeplex.com/workitem/6604 . To put it in a nutshell, the exception "System.Data.ConstraintException: This property cannot be set to a null value" is thrown by Entity's Property Validation. This validation is performed when your mvc application tries to bind the form field to the corresponding entity property( it's called PreBinding Validation, and it occurs when submitting the form). As the field is empty( therefore convert to null), the binder tries to bind a null value to the property, which violates the Non-Null constraint on your entity's property.
But if you post with a blank field ( that is different from empty, therefore null) Entity validation passes( as the property is not set to a null value anymore), and then your see the message from the "Required" annotation validation, that is performed after the prebinding (it's PostBinding Validation).
A workaround is to use the annotation [DisplayFormat(ConvertEmptyStringToNull = false)] that tells to the binder not to convert an empty string to null.
[Required]
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string YourStringProperty { get; set;}
Hope, this helps!
This was very helpful. I'm using MVC3 and entity framework. I was passing my entities directly into the controller, but got the same error when the form was blank. With entity framework you can do data validation by editing the auto-generated code, but creating a separate partial class of the entity worked better for me.
[MetadataType(typeof(TestEntityValidation))]
public partial class TestEntity{
}
public class TestEntityValidation{
[Required]
[DisplayFormat(ConvertEmptyStringToNull = false)]
public String name { get;set}
}
Sometimes in database first approach in EF, may you update your column from not null to can be null using SQL query and use 'Update Model From Database...' (in EDMX right click) then maybe property of that entity not updated properly and so if you have some null data in that column ,in mapping ,violation occurs and this error shown.
To fix this; You can check the Nullable in Properties of that property of entity that you updated it.