Overriding .net mvc framework validations? - asp.net-mvc-3

I have a popupeditform from a grid. I have applied validation rules to the binded model While testing I found that other than user specified validations, some framework generated errors are also coming up.
How can I override those messages
Eg :
This is what I give as validation
[Range(0, 100, ErrorMessage = "Ratio should be between 0 and 100")]
[Required(ErrorMessage = "Ratio is required")]
public double Ratio {get; set; }
During run time I give value "2147483648" which is just above the maximum value. And I am getting error as "Value was either too large or too small for an Int32." If I give a value within permitted range say 2147483647 which is the margin value for int32 then my validation rules gets applied.
So my understaning is that the control comes first to the framework and shows framework validation message first.
In any way can I override the same ?

you mentioned range validation and required validation.If the validation fails due to any other reason it will generated it's message related to error and not your escaped validation message.
you should limit the max length of input. if its double set max length accordingly and similarly for others. so your validation wont have bugs.

Related

Umbraco culture and hostnames affects validation

I've got very wired problem. I have payment page on which I've got amount with custom model. Here is validation for that property:
[Required(ErrorMessage = "Kwota - Pole wymagane!")]
[Display(Name = "Kwota: ")]
[RegularExpression(#"^\d+(\.\d{1,2})?$", ErrorMessage = "Proszę podać poprawną kwotę!")]
[Range(00.01, 99999999999, ErrorMessage = "Kwota musi być większa niż 0.00")]
public decimal Amount { get; set; }
I'm trying to make site in multiple languages so I follow standard umbraco process but once I change language or hostname the above property return:
"The value '1.00' is not valid for Kwota: ."
This doesn't fail if my culture language is inherit and there is no domains added but once I add domain or change culture language it fails. Any idea or reason?
I have checked and it happens on server side as I can hit breakpoint on post action.
I have also noticed that once I change culture and hostnames I'm no longer hitting breakpoint on my custom validation for honeypot witch is on model - I just simply implement IValidatableObject.
Just to clarify I'm running: Umbraco version 7.4.3 assembly: 1.0.5948.18141
Any help very appreciated.

Web application's form validation - design to propagate domain errors to client-side?

Data validation should occur at the following places in a web-application:
Client-side: browser. To speed up user error reporting
Server-side: controller. To check if user input is syntactically valid (no sql injections, for example, valid format for all passed in fields, all required fields are filled in etc.)
Server-side: model (domain layer). To check if user input is domain-wise valid (no duplicating usernames, account balance is not negative etc.)
I am currently a DDD fan, so I have UI and Domain layers separated in my applications.
I am also trying to follow the rule, that domain model should never contain an invalid data.
So, how do you design validation mechanism in your application so that validation errors, that take place in the domain, propagate properly to the client? For example, when domain model raises an exception about duplicate username, how to correctly bind that exception to the submitted form?
Some article, that inspired this question, can be found here: http://verraes.net/2015/02/form-command-model-validation/
I've seen no such mechanisms in web frameworks known to me. What first springs into my mind is to make domain model include the name of the field, causing exception, in the exception data and then in the UI layer provide a map between form data fields and model data fields to properly show the error in it's context for a user. Is this approach valid? It looks shaky... Are there some examples of better design?
Although not exactly the same question as this one, I think the answer is the same:
Encapsulate the validation logic into a reusable class. These classes are usually called specifications, validators or rules and are part of the domain.
Now you can use these specifications in both the model and the service layer.
If your UI uses the same technology as the model, you may also be able to use the specifications there (e.g. when using NodeJS on the server, you're able to write the specs in JS and use them in the browser, too).
Edit - additional information after the chat
Create fine-grained specifications, so that you are able to display appropriate error messages if a spec fails.
Don't make business rules or specifications aware of form fields.
Only create specs for business rules, not for basic input validation tasks (e.g. checking for null).
I want to share the approach used by us in one DDD project.
We created a BaseClass having fields ErrorId &
ErrorMessage.
Every DomainModel derive from this BaseClass & thus have a two extra fields ErrorId & ErrorMessage available from
BaseClass.
Whenever exception occurs we handle exception(Log in server, take appropriate steps for compensating logic & fetch User Friendly message from client location based localized Resource file for message ) then propagate data as simple flow without raising or throwing exception.
At client side check if ErrorMessage is not null then show error.
It's basic simple approach we followed from start of project.
If it's new project this is least complicated & efficient approach, but if you doing changes in big old project this might not help as changes are big.
For validation at each field level, use Validation Application Block from Enterprise Library.
It can be used as :
Decorate domain model properties with proper attributes like:
public class AttributeCustomer
{
[NotNullValidator(MessageTemplate = "Customer must have valid no")]
[StringLengthValidator(5, RangeBoundaryType.Inclusive,
5, RangeBoundaryType.Inclusive,
MessageTemplate = "Customer no must have {3} characters.")]
[RegexValidator("[A-Z]{2}[0-9]{3}",
MessageTemplate = "Customer no must be 2 capital letters and 3 numbers.")]
public string CustomerNo { get; set; }
}
Create validator instance like:
Validator<AttributeCustomer> cusValidator =
valFactory.CreateValidator<AttributeCustomer>();
Use object & do validation as :
customer.CustomerNo = "AB123";
customer.FirstName = "Brown";
customer.LastName = "Green";
customer.BirthDate = "1980-01-01";
customer.CustomerType = "VIP";
ValidationResults valResults = cusValidator.Validate(customer);
Check Validation results as:
if (valResults.IsValid)
{
MessageBox.Show("Customer information is valid");
}
else
{
foreach (ValidationResult item in valResults)
{
// Put your validation detection logic
}
}
Code example is taken from Microsoft Enterprise Library 5.0 - Introduction to Validation Block
This links will help to understand Validation Application Block:
http://www.codeproject.com/Articles/256355/Microsoft-Enterprise-Library-Introduction-to-V
https://msdn.microsoft.com/en-in/library/ff650131.aspx
https://msdn.microsoft.com/library/cc467894.aspx

Allow non filled fields

I have a model for an ASP.NET MVC view containing several properties:
Subject
Message
Id
While subject and message are required, Id isn't required (it's hidden and only set
for an existing entry). Unfortunately, MVC validates it as required ( The If field
is required) even though I haven't set the Required attribute.
Has someone a solution? Haven't found a solution here, maybe just searching wrong...
Kind regards,
Sascha
If Id is an Int... you can try making it Int? (nullable Int).
If it is nullabe, I think MVC will not validate it.
Another way, would be place a default value in that hidden, lets say a "-1"... and on the controller you can check it.
By default, ASP.Net Mvc will treat non-nullable properties as 'required' - even if you do not add the [Required] attrtibute to the property. If your id is of type int - it is not-nullable and therefore required.
You have basically two options:
Change your Id property to int? - ie a nullable int.
Change the default setting for MVC to not regard non-nullable attributes as required.
Option 1 is straight-forward. For option 2 add the following to the Application_Start method in your global.asax
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = true;

ASP.NET MVC 3 - Client-Validation with money field

I did followed this blog here and here.
And i have the following problem.
One field in my form is currecy format, from brazil.
I'm using client-side validation. Everything works great expept one issue.
I have 2 validation:
[DisplayName("Taxa de adesão")]
[MoedaReal(ErrorMessage = "Taxa deve ser numérico")]
[Required(ErrorMessage = "Taxa é obrigatório")]
public decimal ValorAdesao { get; set; }
The rule REQUIRED works ok, the MoedaReal rule works okay.
After these rules are passed ok, one final rule is triggered:
The field Taxa de adesão must be a number
I already tried to change the web.config in this line:
<globalization culture="pt-br" uiCulture="pt-br" />
My numbers format accepcted are these:
1,00
11,00
111,00
1.111,00
11.111,00
111.111,00
1.111.111,00
1.111.111.111.111,00
How can i "fool" .NET to accept this format? Because it expects DECIMAL format instead.
You can't fool the default model binder. It simply tries to parse the request string value into a decimal using the culture specified in your web.config. So because you are also using client validation there might be a culture difference between the client and the server. For example the browser could be configured to use en-US and the server pt-BR and then you might have a problem. You could try this:
<globalization culture="auto" uiCulture="auto" />
This means that the culture used by the server will be dictated by the client. If this doesn't work you have a couple of other possibilities:
Write a custom model binder
Use string instead of decimal and then do the parsing manually

Silverlight 4: Localization of built-in data annotation validation exceptions

I would like use data annotations to handle validation in my Silverlight app. The built-in validation attributes (primarily StringLength and Required) are great, and make life very easy. However, they seem to have one critical flaw. If my locale is set to fr-CA, for example, the validation exceptions are still in English - 'The Name field is required', 'The field Name must be a string with a maximum length of 20', etc.
This is a major problem. It means that if I want localized error messages for the built-in validation attributes, I have to manually add ErrorMessage/ErrorMessageResourceType to every validation attribute on every validatable property in my business layer, and manually add translated strings for every error message.
So... am I missing something here? Is there a way to automatically have the built-in validation attributes localized? Or some other easier way of doing this? Or am I just completely out of luck, and stuck with the manual route?
Any comments or thoughts would be appreciated.
Ok, I got around this by simply subclassing the built-in validation attributes. Problem solved!
internal class LocalizedStringLengthAttribute : StringLengthAttribute
{
public LocalizedStringLengthAttribute(int maximumLength)
: base(maximumLength)
{
}
public override string FormatErrorMessage(string name)
{
return String.Format(CultureInfo.CurrentUICulture, LanguageResources.Resource.Error_StringLength, name, MaximumLength);
}
}

Resources