change validate message in data annotation - asp.net-mvc

my object has field with data type int. when i put in html form in this textbox letter not number the validator say- The field must be a number. how can i change this messages like this
[Required(ErrorMessage = "Введите название")]
[DisplayName("Название")]
public int age { get; set; }

I haven't found a clean way to achieve this using Data Annotations. One way would be to write a custom model binder but this seems like a lot of work to do for such a simple task.
Another way to achieve this is to add an App_GlobalResources folder to your ASP.NET application. Add a resource file called Messages.resx containing a PropertyValueRequired string resource.
PropertyValueRequired = "Some custom error message"
In your Application_Start register the resource class key:
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
DefaultModelBinder.ResourceClassKey = "Messages";
}
Note that ASP.NET MVC 2 uses the PropertyValueInvalid instead of PropertyValueRequired resource key.
IMO using Data Annotations to perform validation logic is limited (maybe in .NET 4 this will change). If you want to have full control over the validation logic I would recommend you using a validation library such as Fluent Validation or xVal.

I ran into the same problem and worked around it by specifying a RegularExpression that only allows positive natural numbers.
[Required(ErrorMessage = "Введите название")]
[DisplayName("Название")]
[RegularExpression(#"^[0-9]+$", ErrorMessage = "Поле возраст не является числом")]
public int age { get; set; }
Not sure if there are any downfalls to this solution. It seems to work fine for me.
PS: If you don't want to allow leading zeroes use "^[1-9]+[0-9]*$".
In retrospect: I have to admit though it's a bit weird to add a regular expression to an integer.

Related

MVC 5 - change Data anotation error message for Integers

In my Mvc5 test project I have a model with a property like the following:
[Required]
[DisplayName("Codigo Cliente")]
public int ClientCode{ get; set; }
the default error message when the user enteres a letter of special character in the editor is:
The field Codigo Cliente must be a number.
How can I modify this? in this case I need to change the language, but in case that I wanted to show a more specific error what can I do?
I have tried with the DataType attribute but the Enum does not have a value that applys for this case (numbers)
Use Range:
http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.rangeattribute.aspx
Or use IntegerOnly from Data Annotations Extensions
http://dataannotationsextensions.org/Integer/Create
The simplest way I found to solve this issue is use String with Range attribute in Data Annotation Model like specify below.
[Required]
[Range(0, int.MaxValue, ErrorMessage = "Codigo Cliente must be a positive or negative non-decimal number.")]
[DisplayName("Codigo Cliente")]
public string ClientCode { get; set; }
In Range attribute you can specify your custom Error Message.
For Interger use int.MaxValue , For double use double.MaxValue like so on.
I hope this will help you a lot.
If you want to specify a message you must use this
[Required(ErrorMessage = "your message")]
If you want to use a lang. based message is not that easy. You can use multiple resource file (for every language you need) and try a custom error binder that extends the DefaultModelBinder and make an override of the method BindModel(), there you can make your custom validation ad use your custom language message.

Custom Validation on Multiple Inputs in ASP.net MVC

After researching various methods to implement custom form validation rules in MVC I have found, what I originally considered to be a straightforward bit of validation, to be rather more complex that I anticipated.
I have 2 text inputs, one or the other (or both) need to be populated. If both are NullOrEmpty we need to throw an error.
I have found DataAnnotations to have it's limitations when attempting to validate on multiple fields, giving me highlighting on both inputs and throwing a single error. Is this some beginners naivity?
I also played around with FluentValidation and was unable to get the results I was after.
Currently I am throwing the error in the Controller using:
ModelState.AddModelError("PropertyName", "You need to enter a Property Number or a Property Name")
ModelState.AddModelError("PropertyNumber", String.Empty)
This gives me highlighting on both fields and server-side validation. I am now finding it difficult binding custom client-side validation without using DataAnnotations.
Does anyone have any advice on how to do this properly? Any help or suggestions would be greatly appreciated. I need validation on the server/client, on both fields, with highlighting and a single error message.
Thanks in advance.
[Fool proof][1] validation library covers almost all kind of validation scenarios.
[RequiredIf]
[RequiredIfNot]
[RequiredIfTrue]
[RequiredIfFalse]
[RequiredIfEmpty]
[RequiredIfNotEmpty]
[RequiredIfRegExMatch]
[RequiredIfNotRegExMatch]
Applied to a Model:
public class CreateUserViewModel
{
[Required]
public string Username { get; set; }
[Required]
public string Department { get; set; }
[RequiredIfEmpty(ErrorMessage="error message"]
public string Role { get; set; }
}

asp.net mvc 3 validation on data type

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.

How to do ASP.NET MVC Model Validation with DataAnnotations where ViewModel contains objects from an external Web Service?

I would like to use DataAnnotations for basic client and server-side validation of my MVC ViewModels. My ViewModel looks like this:
public class MyViewModel
{
public Client Client1 { get; set; }
public Client Client2 { get; set; }
public Product Product { get; set; }
}
So I would like to check that both client objects have a name and telephone number, the product object has a valid numeric price, etc.
The problem I have is that both Client and Product are proxy types generated by Visual Studio from a web service, so I can't directly add the annotation attributes to their required properties.
I've read about using the MetadataType attribute to specify the meta data in an alternative class (with duplicate properties), but in this case I can't even add that attribute to the Client and Product classes.
Or can I? In the Web References folder where my VS solution is saved, there is a folder for the web service namespace containing a file called Reference.cs, which contains the VS generated code for the proxy types.
If I add the metadata to the classes in here, will this work—or is messing about with the generated code a really bad idea? Or is there just a simpler, cleaner way to do this?
After a bit of hunting I found that this is actually remarkably simple—it was just a case of my not knowing exactly what to search for!
You don't actually need to add the MetadataType attribute to the original class definition: you can add it to an empty partial class of the same type (make sure your partial class is in the same namespace as the original type).
Then you just create a "buddy" class containing your validation rules as you would normally:
using System.ComponentModel.DataAnnotations;
namespace WebServiceNamespace
{
[MetadataType(typeof(ClientMetaData))]
public partial class Client
{
}
public class ClientMetaData
{
[Required(ErrorMessage = "Please enter a name")]
public string Name { get; set; }
[Required(ErrorMessage="Please enter a telephone Number")]
public string Telephone { get; set; }
}
}
This works perfectly with the standard Model Binding and requires no access to the original code for the type, so you can easily set up validation rules with DataAnnotations, even for types which aren't part of your code base.
Modifying the generated code would work, so long as you don't regenerate it and write over your modifications. Other than the chance of losing your work if someone generates the reference, there isn't a reason you can't add the metadata references to the proxy classes.
The other alternative is using custom validation, or create a model that you then map the fields to the proxy objects. Creating a model that isn't based on the Client object would be your safest method.
I think it would be cleaner to create a model and then map the fields using AutoMapper and/or Model Generator Helper ( http://modelhelper.codeplex.com/ ).

Conditionally validating portions of an ASP.NET MVC Model with DataAnnotations?

I have certain panels on my page that are hidden under certain circumstances.
For instance I might have a 'billing address' and 'shipping address' and I dont want to validate 'shipping address' if a 'ShippingSameAsBilling' checkbox is checked.
I am trying to use the new DataAnnotations capabilities of ASP.NET MVC 2 (preview 1) to achieve this.
I need to prevent validation of the 'shipping address' when it is not displayed and need to find the way way to achieve this. I am talking mainly server side as opposed to by using jquery.
How can I achieve this? I have had several ideas, related to custom model binding but my current best solution is below. Any feedback on this method?
For the CheckoutModel I am using this approach (most fields hidden):
[ModelBinder(typeof(CheckoutModelBinder))]
public class CheckoutModel : ShoppingCartModel
{
public Address BillingAddress { get; set; }
public Address ShippingAddress { get; set; }
public bool ShipToBillingAddress { get; set; }
}
public class Address
{
[Required(ErrorMessage = "Email is required")]
public string Email { get; set; }
[Required(ErrorMessage = "First name is required")]
public string FirstName { get; set; }
[Required()]
public string LastName { get; set; }
[Required()]
public string Address1 { get; set; }
}
The custom model binder removes all ModelState errors for fields beginning with 'ShippingAddress' if it finds any. Then 'TryUpdateModel()' will return true.
public class CheckoutModelBinder : DefaultModelBinder
{
protected override void OnModelUpdated(ControllerContext controllerContext,
ModelBindingContext bindingContext) {
base.OnModelUpdated(controllerContext, bindingContext);
var model = (CheckoutModel)bindingContext.Model;
// if user specified Shipping and Billing are the same then
// remove all ModelState errors for ShippingAddress
if (model.ShipToBillingAddress)
{
var keys = bindingContext.ModelState.Where(x => x.Key.StartsWith("ShippingAddress")).Select(x => x.Key).ToList();
foreach (var key in keys)
{
bindingContext.ModelState.Remove(key);
}
}
}
}
Any better solutions?
http://bradwilson.typepad.com/blog/2009/04/dataannotations-and-aspnet-mvc.html
I can see your predicament. I'm looking for other validation solutions also with regard to complex validation rules that might apply to more than one property on a given model object or even many properties from different model objects in a object graph (if your unlucky enough to be validating linked objects like this).
The limitation of the IDataErrorInfo interface is that a model object satisfies the valid state simply when none of the properties have errors. This is to say that a valid object is one where all of it's properties are also valid. However, i may have a situation where if property A, B and C are valid - then the whole object is valid.. but also if property A is not valid but B and C are, then the object satisfies validity. I simply have no way of describing this condition/rule with the IDataErrorInfo interface / DataAnnotations attributes.
So i found this delegate approach. Now many of the helpful advancements in MVC didn't exist at the time of writing this article but the core concept should help you. Rather than using attributes to define the validation conditions of an object we create delegate functions that validate more complex requirements and because they're delegated we can re-use them. Sure it's more work, but the use of delegates means that we should be able to write validation rule code once and store all the validation rules in the one place (maybe service layer) and (the kool bit) even use the MVC 2 DefaultModelBinder to invoke the validation automatically (without heaps of checking in our controller actions - like Scott's blog says we can do with DataAnnotations. Refer to the last paragraph before the 'Strongly Typed UI Helpers' heading)!
I'm sure you can beef the approach suggested in the above article up a little with anonymous delegates like Func<T> or Predicate<T> and writing custom code blocks for the validation rules will enable cross-property conditions (for example the condition you referred to where if your ShippingSameAsBilling property is true then you can ignore more rules for the shipping address, etc).
DataAnnotations serves to make simple validation rules on objects really easy with very little code. But as your requirements develop you will need to validate on more complex rules. The new virtual methods in the MVC2 model binder should continue to provide us with ways of integrating our future validation inventions into the MVC framework.
Make sure the fields you don't want validated are not posted to the action. We only validate the fields that were actually posted.
Edit: (by questioner)
This behavior has changed in MVC2 RC2 :
Default validation system validates
entire model The default validation
system in ASP.NET MVC 1.0 and in
previews of ASP.NET MVC 2 prior to RC
2 validated only model properties that
were posted to the server. In ASP.NET
MVC 2, the new behavior is that all
model properties are validated when
the model is validated, regardless of
whether a new value was posted.
Applications that depend on the
ASP.NET MVC 1.0 behavior may require
changes. For more information about
this change, see the entry Input
Validation vs. Model Validation in
ASP.NET MVC on Brad Wilson’s blog.
For the more complex cases I moved away from simple DataAnnotations to the following: Validation with visitors and extension methods.
If you want to make use of your DataAnnotations you would replace something like the following:
public IEnumerable<ErrorInfo> BrokenRules (Payment payment)
{
// snip...
if (string.IsNullOrEmpty (payment.CCName))
{
yield return new ErrorInfo ("CCName", "Credit card name is required");
}
}
with a method to validate a property by name via DataAnnotations (which I don't have atm).
I created a partial model binder that only validates the keys that were submitted. For security reasons (if I was going to take this a step farther) I'd create a data annotation attribute that marks which fields are allowed to be excluded from a model. Then, OnModelUpdated check field attributes to ensure there is no undesired underposting going on.
public class PartialModelBinder : DefaultModelBinder
{
protected override void OnModelUpdated(ControllerContext controllerContext,
ModelBindingContext bindingContext)
{
// default model binding to get errors
base.OnModelUpdated(controllerContext, bindingContext);
// remove errors from filds not posted
// TODO: include request files
var postedKeys = controllerContext.HttpContext.Request.Form.AllKeys;
var unpostedKeysWithErrors = bindingContext.ModelState
.Where(i => !postedKeys.Contains(i.Key))
.Select(i=> i.Key).ToList();
foreach (var key in unpostedKeysWithErrors)
{
bindingContext.ModelState.Remove(key);
}
}
}
This isn't related to DataAnnotations but have you looked at the Fluent Validation project? It gives you fine grain control over your validation and if you have object-to-object validation an aggregate object of the two objects will get you going.
Also it seems to have been build with MVC in mind but it also has its own "runtime" so that you can use it in other .NET applications as well which is another bonus in my book.

Resources