input-validation-error on other input element?
I have a model which has 2 fields, "a" and "b" like this:
class AbModel
{
public string a {get;set;}
[SomeValidation]
public int b {get;set;}
}
Now "b" is actually hidden in the gui, and "a" shows a textual representation of it.
<div class="editor-field">
<%= Html.HiddenFor(model => model.b, new { id = "ABModelEditor_b" })%>
<%= Html.TextBoxFor(model => model.a, new { id = "ABModelEditor_a" })%>
<input type="button" value="Change" onclick="AbModelEditorScript.showAbSelector(); return false;" />
</div>
Generates the following on "save" with empty data:
<div class="editor-field">
<input class="input-validation-error" id="ABModelEditor_b" name="b" type="hidden" value="">
<input id="ABModelEditor_a" name="a" type="text" value="">
<input type="button" value="Change" onclick="AbMod开发者_高级运维elEditorScript.showAbSelector(); return false;" />
</div>
I need the the input-validation-error css class to be attached to the "a" textbox instead of the hidden for "b".
Before I simply move the css-class with a jquery-script, is there some other way that I should consider, perhaps some built in functionality?
Are you using unobtrusive validation? The other option is to add the validation attributes with jQuery and revalidate the form...
$("#ABModelEditor_a").attr("data-val-required", "true"); //add your validation attributes to the input tag
var form = $("form");
form.removeData("validator").removeData("unobtrusiveValidation") // this will clear the validation from the form
$.validator.unobtrusive.parse(form); //reattach the validation
This will give you real client side validation, but it still won't match your model. You'll have to fill in the gap on the server side.
In regards to your comment about server-side only validation.
You can try to manually add the model error to the model state. This should be reflected in your view when you return.
ModelState.AddModelError(string key, string errorMessage);
精彩评论