c# - Putting form validation on html controls in razor engine -
i have been facing issue of putting form validation on html controls 1 guide me how resolve issue?
my html field in something.cshtml
<input type="text" id="accidentdate" name="accidentdate" /> @html.validationmessage("accidentdate")
controller code:
[httppost] [allowanonymous] public actionresult index(models.c objc) { if (string.isnullorempty(objc.accidentdate)) { modelstate.addmodelerror("accidentdate", "*"); } return view(objclaimant); }
please note validationmessage raise error in form of * in-front of input field requirement highlight input field red.
most important know if use: @html.textbox("accidentdate", model.accidentdate);
works using not requirement.
finally, looking make html input field red through other way, if validation message raised.
any appreciated.
ok, rather commenting figured i'd try , help. i'm presuming want use unobtrusive validation engine
so if
@html.textbox("accidentdate", model.accidentdate);
and view source you'll see like:
<input data-val="true" data-val-required="the accidentdate field required." id="accidentdate" name="accidentdate" type="text" value="">
so important thing notice data-val
attributes. these tell unobtrusive engine, "this field needs validated , how , display if fails"
so without @html.textbox
which you, you'll need create these attributes in html.
quick dirty solution, put @html.textbox
in, run code cut&paste html. may not want?
edit want required validation, above data-val="true" data-val-required="the accidentdate field required."
attributes need, substituting own error message
so:
<input type="text" id="accidentdate" name="accidentdate" data-val="true" data-val-required="the accidentdate field required." /> @html.validationmessage("accidentdate")
css class
the css class should being applied. relevant piece of code is:
function onerror(error, inputelement) { // 'this' form element var container = $(this).find("[data-valmsg-for='" + escapeattributevalue(inputelement[0].name) + "']"), replace = $.parsejson(container.attr("data-valmsg-replace")) !== false; container.removeclass("field-validation-valid").addclass("field-validation-error"); error.data("unobtrusivecontainer", container); if (replace) { container.empty(); error.removeclass("input-validation-error").appendto(container); } else { error.hide(); } }
inside jquery.validate.unobtrusive.js
. confirm referencing js file , see if above code hit?
Comments
Post a Comment