Can Fluent Validation .NET determine error messages sequence - asp.net-mvc

I use Fluent Validation .NET for validating.
Is it possible to determine error messages sequence from "RuleFor" in validation summary.
Example:
RuleFor(x=>x.A).NotEmpty().WithMessage("A is required.");
RuleFor(x=>x.B).NotEmpty().WithMessage("B is required.");
For example, How can I determine message sequence to specificly show "B is required." before "A is required".

There is no explicit ordering of rules inside FluentValidationModelValidationFactory validator queries, that means that order of error messages on server-side depends on order of rules declaration, e.g. if rule for A property goes before rule for B, then you will see in ValidationResult error message for A before B. But it works only for manually getting of validation result (create validator object and call Validate method).
After errors get into ModelState object - they loss their order. Thats because of ModelStateDictionary type, which stores objects as Dictionary, not as List.
And if we look at NDoc description of ValidationSummary method, we see:
Returns an unordered list (ul element) of validation messages that are in the ModelStateDictionary object.
But if client-side validation enabled - then validation summary element appears without server call, and it's error messages order the same as order of inputs in html.
Conclusion
The only way to save error message order in ViewResult is to 'manually' use validator, call validate and manually iterate ValidationResult in partial view or template to create markup you need. But if you rely on client-side validation — you can just reoder inputs on form.

Related

Validation Message is shown even there is no error message

I have created a form along with other fileds having validation and there is one field where it doesn't have the validationMessageFor but in validationSummary I am able to see the error for that field and model doesn't have the required property.
Validation summary Is supposed to display all the error messages on the model irrespective of validationMessageFor usage in UI.
The field might contain any other validations associated with it. Please post your model here.

Why JSP doesn't throw error for non-mapped fields in Struts 2

I've my Struts 2 actions as ModelDriven. I've some fields defined on the actions themselves as well. However, if in the JSP I use wrong field names that are neither in ModelDriven model nor directly used as action member fields then I don't get any errors and it simply ignores those fields.
<s:if test="(method == 'list')">
If method is neither a ModelDriven model field nor an action member field then it simply ignores this s:if statement and doesn't execute instructions inside this s:if statement.
Any idea on how to throw errors on JSP for fields that are non-mapped in the ModelDriven models fields or in the actions of ModelDriven models?
OGNL expressions can throw exceptions but they are caught internally.
The OGNL expression is evaluated in this attribute, like in many other
attributes of Struts tags, and if can't resolve the value it returns
null. This value is unacceptable for the if tag.
However, if you know which expression returns null then create a boolean expression.
Any idea on how to throw errors on jsp...
The java code is encapsulated in the tags implementation. If tags cannot execute they throw 500 internal server error. You can write your custom tags to throw that errors.

MVC Show different ValidationSummary ErrorMessage compared to ValidationMessage

In ASP.NET MVC, is it possible to show a different message in the ValidationSummary compared to what is shown in the ValidationMessage?
IE - if i have a FirstName textbox, on validation the message next to the text box will say 'You need to fill this out', but in the validation summary it will say 'Please provide a first name'.
I'm not sure if I completely understand what you are trying to accomplish, but you can specify a generic error message in the validation summary. In your view you can use:
#Html.ValidationSummary(true, "Please correct the errors below")
The boolean parameter indicates whether you want to exclude property errors. The string is the message you want displayed. Using this overload the way I have above, the model-level error message Please correct the errors below would be shown in place of the #Html.ValidationSummary() method, and the property errors would be shown where you place your #Html.ValidationMessageFor() methods.
See the MSDN documentation for a complete list of overloads.
Yes. It should be quite obvious from looking at the intellisense.
you would say:
#Html.ValidationSummary(true)
and it will contain the error messages that are located on the model or the default messages
And you can say:
#Html.ValidationMessageFor(m => m.Property, "This is a custom message")
And that overrides the message on the individual message.
Also, keep in mind that #Html.ValidationSummary(true, 'Header Message') will show your custom summary message along with the same messages that you provided in your model data annotations.
i.e. in your model class:
[Required(Message="First name is required")]
public string FirstName { get; set; }
Your validation summary would look some like this:
Header Message
First name is required
Alternatively, you can build up a custom collection of messages by using ModelState.AddModelError("Key", "Message") in your controller, then referencing that key in your view using ViewData.
After looking at the Metadata available, I don't think what I want to do is possible. What I'm going to do instead is type in the input specific value for validation, and hide the class field-validation-valid.
Providing different Errormesages beside the input fields and in the Validation Summary is not possible with #Html.ValidationSummary. Such a feature could make sense because a part of the errormessage's information can come from it's position in the page (e.g. beside a firstname input field the message could be 'Input required' and in the validation summary you need 'Input required for firstname'). Unfortunately a poor implementation for ValidationSummary in MVC, .net 2.0 provided the feature to have different messages in it's validators and in the validationsummary .

Exclude ID property from xVal validation

Can I exclude the valudation rule for the ID property? Right now I get the following validationerror message when I submit the form:
The Id field is required.
From http://xval.codeplex.com/Thread/View.aspx?ThreadId=54212
getting a ModelState.IsValid = false with a message of “ID is Required”
I think you're talking about server-side validation here. Remember that xVal's key job is enabling client-side validation, where this problem doesn't occur. On the client, you won't create a textbox for "ID" (because you wouldn't want the user to edit it directly) - at least not during the creation phase - so the client-side validator would ignore the ID property, not attempting to validate it because there's no input control to validate.
On the server, the behaviour will vary according to which validation runner you're using.

How do I get database validation among my rule violations on ASP.NET MVC?

On the NerdDinner example a set of business rules are written to validate the data on a model. Things like empty strings are checked for and by calling modelObject.GetRuleViolations() you can get them all. But there's another layer of validation which is the database. For example, the datetime field is left for validation to the database, which only accepts a string that can be converted into a DateTime object.
The problem I see is that modelObject.GetRuleViolations() never return the violation for datetime. So even when it is correctly prevented from saving the record and the form is shown back specifying there's an error and highlighting the datetime field, there's no specific error message. Is there a way to get the database validation errors among the business rules validation errors?
You need to catch the exceptions thrown by your Data Access Layer, and convert those into calls which update the ModelState to indicate the errors in question. There's not really a good way to do this on a global level, since specific SQL errors will only be able to be interpreted at the time they're called, rather that handled in a generic way.
I don't remember the exact code from NerdDinner, though I have looked at it. However, in my applications, I typically do a raiserror('Some error',16,1) in the database and use a try/catch in my controller / model like so:
public void DoSomething()
{
try
{
// Some database activity
}
catch (SqlException ex)
{
ViewData["ErrorMessage"] = ex.Message;
}
}
I can then render the error in my view however I want.
Your assumption is wrong. The datetime field is not left for validation on the database.
One thing I had to grok in the NerdDinner/MVC lessons was that validation will occur in both the Dinner.cs OnValidate() partial method and in the DinnersController.cs in the call to UpdateModel(). This call copies the text from the screen into the Model. If, for example, it tries to copy text to a float, or parse and invalid date, it will update the ModelState and throw an error. The normal validation will not run.

Resources