Exclude ID property from xVal validation - asp.net-mvc

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.

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.

Can Fluent Validation .NET determine error messages sequence

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.

Why can't you add a EditorExit Handler to a DynamicForm or FormItem?

This handler only exist for a ListGrid.
But if you look at the docs for DynamicForm.setValidateOnExit(), it says:
If true, form items will be validated when each item's "editorExit"
handler is fired as well as when the entire form is submitted or
validated. Note that this property can also be set at the item
level to enable finer granularity validation in response to user
interaction - if true at either level, validation will occur on
editorExit.
So how can we add a EditorExitHandler to a DynamicForm or a FormItem?
EDIT :
I want to create an error panel below the form to show all errors dynamically. Each FormITem has the possibility to validate on Exit but I do not know how to capture this validation event to check if the error panel should be updated or not.
There is one method form.getErrors() and form.showError(true). By this you can acheive that. But for that also you need to setValidator for each field.
TextItem name = new TextItem("name", "Name");
name.setRequired(true);
name.setRequiredMessage("Please specify name of the Table");
NTRegExpValidator nameValidator = new NTRegExpValidator("(^[a-zA-Z0-9][\\w\\s.()_-]+)$","It should start with alphabets and can have alphanumeric values ( )_-. and space.");
name.setValidators(nameValidator);
name.addKeyUpFieldHandler(new KeyUpHandler){
form.getErrors();
form.showErrror(true);
});
DynamicForm form = new DynamicForm();
form.setField(name);
After some research, I still don't find a convincing answer. I guess it must a dev requirement

Display errors using Knockout JS + MVC + Server-side Model Validation?

Html form is controlled using Knockout JS and jQuery templates.
Basic jQuery validation is in use to validate fields.
Form gets serialized to JSON and submitted to MVC controller action using AJAX.
MVC controller action performs server-side model validation, adds errors to ModelState.
What's the best practice to return those errors to the client - iterating through errors in ModelState and adding them to key/value collection of errors in the JSON response?
How do you display errors on the client? How do you 'bind' the key/value collection of errors to relevant fields on the model?
Say there is a "name" field on the model, with a corresponding textbox rendered by the jQuery template. How does one take the error for the "name" field in the collection of errors and display the error message beneath the "name" textbox?
There's two validation plugins for ko.js (found here) that could help you,
Knock-Knock validation
Knockout Validation
You can wire one of those to the mvc unobstrsive validation data injected client side.
If you are using MVC, unobtrusive javascript performs client side validation based on the validation set in your model. You need not perform any additional configuration.
Having said that, there is no direct way to perform client side validation based on the model using javascript and knockoutjs.
There are couple of ways of doing it on the client side.
Jquery or any other validation frameworks can perform validation. But you need to have tag. Advantage with this approach is your code will be simple and easy to maintain.
You can perform client side custom validation using javascript and bind the validation messages using knockout. This requires you to create error labels for each of the input variable. Advantage with this approach is you will have complete control over how and what has to be displayed.
Personally, I had similar requirement in one of the recent projects and I achieved it using custom validation checks and error labels.

Why does the default model binder not validate fields when they are not in form data?

Let's say you have simple object like this :
public class MyObject {
public int Test { get; set; }
}
And you count on the default model binder to make sure the user does not leave the "Test" field empty when posting a form like below :
<form method="post" action="/test">
<p>
<%=Html.TextBox("Test") %>
<%=Html.ValidationMessage("Test") %>
</p>
<input id="Submit1" type="submit" value="submit" />
</form>
And this action :
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Test(MyObject o) {
return View();
}
This all works as expected when the form data contains a key for "Test" (like "Test=val" or "Test=")
But if the key is not in the form data, then the validation doesn't occur. So in case of an empty post request or a request with a data like AnotherField=foo the property on the model object defaults to the type's default value (in this case 0). And ModelState.IsValid returns true.
This is, IMO, not the behaviour one would expect.
So what do you suggest to change this behaviour?
Edit :
Keep in mind that a malicious user can just tamper the form data easily with FireBug or Tamper Data plugin to pass the default model binder's validations, which could cause some security problems.
It is not validating the fields by design, unfortunately. Please take a look at this Codeplex issue that I've found and commented on.
It is really unfortunate, that MS has decided this is the correct behaviour for their model binder.
I believe the default model binder should validate the whole entity instead of just the posted data.
You might consider using xVal to perform the necessary mix of client- and server-side validation. With it, you can add an attribute to your Test property dictating what sort of validation rules (required, regex validation, etc.) apply to it and then, with a little more work, get it to generate JavaScript rules for you as well as pretty easily perform model validation.
You're already aware that you're violating a rule of development - never trust client input. There's really no way around it.
Client-side validation (preventing a round trip to find out that there's an error) is nice-to-have, server-side validation verifying that things truly are in order is a must-have.
i hope its by design because I am about to start relying on this behavior!
in one instance i have two controls which post back the following fields :
ShippingAddress.FirstName
ShippingAddress.LastName
ShippingAddress.Line1
ShippingAddress.Line2
BillingAddress.Email
BillingAddress.FirstName
BillingAddress.LastName
BillingAddress.Line1
BillingAddress.Line2
Note: Billing Address does not have email displayed, even though the underlying model of course still has it
If I have Email as a [Required] data annotation in my model then it will only complain when it is missing from Billing Address.
But I definitely see your point! I'm just relying on it for this one scenario here!
After researching all the different ways to get the form values into my controller methods, I discovered that the "safest" was to explicitly define each form field as a parameter to the controller. A side effect is that if a form does NOT have one of the fields, it will throw an exception - which would solve your problem.

Resources