4

I’ve a small problem with model validation.

I have a hidden field called “theID” and a textbox called “theDesc”. The field theDesc is an autocomplete, and when I select it, theID get the id stored.

theID is the field that is stored in database, and is the one that is “Requiered”, so I use: @Html.ValidationMessage("theID")

The problem is that the CSS class input-validation-error is assigned to the hidden field. I now this behavior it’s normal and expected, but there is a way to change this?

what I want to accomplish is that the theDesc field shows the input error class. This way the user can notice that is missing.

Is not a big deal, but my OCD is driving me crazy about not get all the errors with the same style.

epaulk
  • 309
  • 1
  • 4
  • 15

2 Answers2

3

Good question and nicely phrased! I had exactly the same question, but see no definitive answer yet. I managed to do it - at least with server side validation - by adding a server side validation in the controller and in the view using HTML helpers instead of custom HTML. This post helped me:

.input-validation-error to a textbox when the form is redisplayed for failed value

As mentioned in the post it is necessary to set the name of the html e.g. model field correctly. So I added some server side validation code in the controller. Notice how the checked field model.theID is different from the name added in the ModelState "TheDesc":

Controller code:

public ActionResult SomeActionIndex(SomeModel model) {
   ...
   if (string.IsNullOrEmpty(model.theID) {
        ModelState.AddModelError("theDesc", "The field is uhm... required!");
   }
   ...
}

The comments in the post indicate that for highlighting (red border via the CSS class) it helps to use the standard HTML helpers as these automatically enable the use of the jQuery validation. In my case the validated autocomplete list was initialy NOT generated using an HTML helper but some custom HTML inside a nested view. I changed this.

View code:

@Html.TextBoxFor(m => Model.theDesc, new { @class="auto-complete", 
@placeholder="choose a value..." })

@Html.TextBoxFor(m => Model.theID, new { @style = "display: none" })

Note: Precisely the kind of black magic that the HTML helpers do to make this work I haven't been able to figure out yet. So I'll leave it till later, or for somebody else, but I think this question relates to it:

custom htmlhelper with validation support

Community
  • 1
  • 1
Bart
  • 5,065
  • 1
  • 35
  • 43
0

On the change event of your autocomplete assign that value to your hidden field.

Har
  • 4,864
  • 2
  • 19
  • 22