RIA service default required attribute - validation

I have an EF4 model with table's columns doesn't allow null.
At the SL client application I always receieve the "columnName is required" because I have the binding in xaml with [NotifyOnValidationError=True,ValidatesOnExceptions=True] for the textboxes.
My questions is:
I can overide the default required errormessage at the metadata class, but how can I have it as a custom validation? I mean I don't wnat to do this at the sealed metadata class:
[Required(ErrorMessage = "Coin English Name Is required")]
[CustomValidation(typeof (CustomCoinVaidation), "ValidateCoinName")]
public string coin_name_1 { get; set; }
I want to have it inside the custom validation method that I will define for all types of errors regards that coin_name_1, as follows:
public static ValidationResult ValidateCoinName(string name, ValidationContext validationContext)
{
if (string.IsNullOrWhiteSpace(name))
{
return new ValidationResult("The Coin Name should be specified", new [] { "Coin Name" });
}
return ValidationResult.Success;
}
Why?
for two reasons :
1- Group all the validation isdie one container (for easy localization further).
2- I don't want the coin_name_1 to be displayed to the end-user, but a meanigful as "Coin English Name".
Second question:
I have a ValidationSummary control on my xaml page where all the errors are displayed but is displaying the orignal name of the column "coin_name_1" how can I chnge that to be a meanigfil also.
Best regards
Waleed

A1:
I just left the required as it is implemented right now..
A2:
I went through different sources and find this artical.
It shows how to style the validation summary:
http://www.ditran.net/common-things-you-want-know-about-silverlight-validationsummary
I am also implementing a client-side validation asyncronizly.
Regards

Related

MVC3 Error message globalization

I'm really lost trying to create custom generic validation messages for my MVC3 application.
I read many tutorials and the biggest part of them suggest one of these options:
Create an App_GlobalResources folder and inside that put my custom resource, them I change global.asax, passing the string name of my resource to DefaultModelBinder.ResourceClassKey property. Change the resource's build action to "Embeded Resource".
Right click the project, then go properties, click "Resources" tab and create your custom resource. Set it's access modifier to "Public".
The first one didn't work to me, I have the following keys in my resource:
DefaultModelBinder_ValueRequired, InvalidPropertyValue, PropertyValueInvalid, PropertyValueRequired
and none of them was used when my I tried to submit and form with empty value in a required attribute of my model.
I've put this code at global.asax Application_Start method:
DefaultModelBinder.ResourceClassKey = "My_Resource_Name";
With the second method, I've created an resource with the same keys as the first one. None of them was used by default when a property is invalid or empty (I've changed the ResourceClassKey in global.asax too, but without success). But when I added some parameters to data annotation in my model:
[Required(ErrorMessageResourceType = typeof(MyResourceFile), ErrorMessageResourceName = "MyCustomKey")]
When the attribute of that data annotation is empty, my message defined with "MyCustomKey" is used!
But I really don't want to manually set this to all my attributes, I want to replace the default error messages like: "The {0} field is required."
That message is part of DataAnnotations. The default message is compiled into the DataAnnotations assembly in the resource file under System.ComponentModel.DataAnnotations.Resources.DataAnnotationsResources.resources and is RequiredAttribute_ValidationError=The {0} field is required. You can try to download the source, change that part and rebuild it.
There doesn't seem to be a simple global way of changing it. You could try this, otherwise it looks like you are stuck with adding your attribute to every field. Or use something like this:
public class SomeModel
{
[Required(ErrorMessage = "The article is required")]
public string Article { get; set; }
[StringLength(512, ErrorMessage = "Must be less than 512 characters.")]
public string URL { get; set; }
}

MVC3 validate only one entity in ViewModel

I have an mvc3 create page using a View Model with 2 entities
like
class ViewModel1{
public User user{get;set;}
public Company company{get;set;}
}
where User and Company are EF4 entities(tables). I need to use a single page to create both(related) tables. Now the Company entity is optional under some conditions and I use jQuery to hide the corresponding section in the view.
However since company has required fields , the post back create function has ModelState.Valid as false.
What I want to do is if the Company section is hidden, I would like to skip validating the Company entity in ViewModel in Server( I avoid validation of hidden elements in Client).
Maybe there is a better and more proper approach to this?
What you have shown is not a view model. You call it a view model but it isn't because it is referencing your EF domain entities.
A more realistic view model would look like this:
class ViewModel1
{
public UserViewModel User { get;set; }
public CompanyViewModel Company { get; set; }
}
or even flattened out and containing only the properties that your view needs:
class ViewModel1
{
public int UserId { get;set; }
[Required]
public string FullUserName { get;set; }
[Required]
public string CompanyName { get; set; }
}
Now depending on your specific requirements about view model validation your UserViewModel and CompanyViewModel classes will be specifically designed for them.
Instead of putting the entities directly in the view model, put the properties for the entities in the view model and map between the view model and the actual entity objects on the server. That way you can control what properties are required for your view. Create some custom validation rules to validate that the required company properties are there when some company information is required. To do this on the server, you can have your view model implement IValidatableObject and implement the logic in the Validate method. On the client you can add rules to the jQuery validate plugin for the "required if" properties.
public class UserCreationViewModel : IValidatableObject
{
[Required]
public string Username { get; set; }
[Required]
public string FirstName { get; set; }
...
public string CompanyName { get; set; }
public string CompanyEmail { get; set; }
public IEnumerable<ValidationResult> Validate( ValidationContext context )
{
if (!string.IsNullOrEmpty(CompanyName) && string.IsNullOrEmpty(CompanyEmail))
{
return yield new ValidationResult("Company Email is required if you specify a company", new [] { "CompanyEmail" });
}
}
}
I'm not sure what I would do on the client-side. You have a choice of either adding specific rules to the validate plugin directly, but it might be hard to make it look exactly the same as using the unobtrusive validation that MVC adds. Alternatively, you could look at adding/removing the unobtrusive attributes from the "required if" elements using jQuery depending on the state of the elements that trigger their requirement. I suggest trying both ways -- look at the docs for the validate plugin to see how to add custom rules and examine the code emitted by the MVC framework for the unobtrusive validate to see what you would need to add to make that work.
Another possibility would be including/removing a partial view with the company properties in the from based on whether the company information is required or not. That is, type in a company name and use AJAX to grab the inputs required for the company and add them to the form. If the company name is deleted, delete the elements. Leave the server-side validation the way it is, but in the partial view mimic the HTML that the framework would add in for unobtrusive validation. This is sort of the best of both worlds as the jQuery code is much simpler and you get consistent validation, too.
There are many ways you can achieve,
1) more commonly donot use [Required] attribute on Company object, but have proper validation for parameters inside Company object.
In this case if Company object is null still validation will pass, but if Company object isnot null it will validate each properties.
2) If validation involves some complex business logic, then go for Self Validating Model. (inherit from IValiddatableObject, and override Validate(...).
3) By code, in the controller.
if(model.company == null)
this.ModelState.Keys.Where(k => k.Contains("company")).ToList().ForEach(k => this.ModelState.Remove(k));
first two are best approved approaches, third is just another way to achieve your functionalities

Validating parameters passed through the URL

I am working on an ASP.Net MVC3 application and I'm having trouble understanding the "right way" to do the validation I'm looking for.
For example, consider a model that looks like this:
[Required]
[StringLength(10, MinimumLength = 10)]
[RegularExpression("[0-9]{10}")]
public string Id { get; set; }
[Required]
public string Value { get; set; }
If I have an Id of "2342" and try to POST back, the model mapping kicks in and registers an error because of the length validation. However, if perform a GET against /controller/2342, then MVC seems to happily create a model with this invalid state (ModelState.Valid will be true). I could create some validations in the controller to catch this, but it seems redundant.
What is the best way to do this?
Thanks!
Jacob
When you perform a GET, you are simply retrieving a model with a given ID. So there is no validation performed. If you really want to make sure that requested model IDs should be 10 numbers in length, you should define constraint in Global.asax:
routes.MapRoute(
"Product",
"Product/{productId}",
new {controller="Product", action="Details"},
new {productId = #"[0-9]{10}" }
);
There is nothing in the framework that by default validates a model on a GET request as validation isn't generally required at that time. If you do want to force a validation here, this was answered in this prior question
See:
Validate model on initial request

.NET MVC3 Remove Currency Symbol and Commas

In my model I have the following property:
[DataType(DataType.Currency)]
public decimal? Budget { get; set; }
When the user enters in $1,200.34, I need that value to be valid and strip out the currency symbol and comma.
In my controller I'm doing:
if (race.Budget != null)
{
race.Budget.ToString().Replace("$", "").Replace(",", "");
}
The problem is that client validation doesn't pass the value for budget into the controller. I get a value of null. How can I override the client validation so that I can strip out the currency symbol and comma?
Thank you in advance for the help.
UPDATE
So here's the strange thing. Let's say I want to bypass client validation all together. I added #{ Html.EnableClientValidation(false); } to my view and it's still sending a null value for Budget when I submit to the controller.
This isn't a client side validation problem. Your model has a field of type decimal? The model binder will try to bind a value of $123,456.78 into that and fail, so the value will be null. Here's one way to get around this:
Change your model to have a string property that masks your decimal:
public decimal? Budget { get; set; }
public string BudgetText {
get {
return Budget.HasValue ? Budget.ToString("$") : string.Empty;
}
set {
// parse "value" and try to put it into Budget
}
}
Then, just bind to BudgetText from your View. Validate it as a string with a regular expression that accepts only money input. It'll probably be the same regex you can use for your BudgetText's set method
So you can probably hook in some JQuery to pre-process the form field to strip the characters off you don't want (prior to form submission to the server). This is probably the quickest, dirtiest approach.
For something reusable, have a look into custom client validation adapters. The links aren't spot on, but should get you in the right direction. For Brad's screencast, I believe the relevant parts are fairly early on.
Check out the support for jQuery localization
cliente validation using jQuery validate for currency fields
also there is a plugin for currency validation as well
http://code.google.com/p/jquery-formatcurrency/
check out this recent post as well for a $ in binding
.NET MVC 3 Custom Decimal? Model Binder

How do I show a different Required message to instances of the same object in MVC3?

I have a Razor MVC3 project which has two user records in a form, one for the key contact and one for a backup contact. For example;
public class User
{
[Required(ErrorMessage = "First name is required")]
public string FirstName { get; set; }
}
Validation all works well except for the small issue where the user fails to fill out a field, it says 'First name is required' but I'd like to point the user to which one of the first name fields is missing. Such as 'Backup contact first name is required' or 'Key contact first name is required'.
Ideally I'd like to leave the [Required] annotation on the class as it is used elsewhere.
This seems like one of those small cases that might have been missed and is not easily achieved, but please prove me wrong.
Ryan
One way you can accomplish this is with a separate view model for this screen, instead of a single User model with all the error messages. In the new view model, you could have a BackupContactFirstName property, KeyContactFirstName property, etc each with its separate error message. (Alternatively this view model could contain separate User models as properties, but I've found that Microsoft's client validation doesn't play well with complex models and prefers flat properties).
Your view model would look like this:
public class MySpecialScreenViewModel
{
[Required(ErrorMessage = "Backup contact first name is required")]
public string BackupContactFirstName { get; set; }
[Required(ErrorMessage = "Key contact first name is required")]
public string KeyContactFirstName { get; set; }
}
Then pass your view model to the view like this:
#model MySpecialScreenViewModel
...
Your post controller action would collect the properties from the view model (or map them to separate User models) and pass them to the appropriate data processing methods.
An alternative I have stumbled across, just modify the ModelState collection. It will have the elements in a collection named by index, like 'User_0__EmailAddress' and you can adjust / amend / replace the Errors collection associated with that key.
[Required(ErrorMessage = "{0} is required")]
{0}=The DisplayName is automatically placed on it
sample
[DisplayName("Amount per square meter")]
[Required(ErrorMessage = "{0} is required")]
public int PriceMeter { get; set; }
output
Amount per square meter is required

Resources