MVC validation with autocomplete field

Small problem with model validation.

I have a hidden field called "theID" and a text field called "theDesc". TheDesc field is autocomplete and when I select it the ID gets the ID.

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

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

what i want to do is that the theDesc field shows the class of input errors. Thus, the user can notice what is missing.

Not much, but my OCD is driving me crazy not to get all the errors with the same style.

+3


source to share


2 answers


Good question and beautifully worded! I had exactly the same question, but no definitive answer yet. I have succeeded in doing this - at least with server side validation - by adding 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 the textbox when the form is re-rendered for a failed value

As mentioned in the post, the html name needs to be specified, eg. right. So I added some server side validation code to the controller. Notice how the checked field model.theID differs from the name added to 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 through CSS class) it helps to use the standard HTML helpers as they will automatically trigger the use of jQuery validation. In my case the checked autocomplete list was initialized NOT generated using the HTML helper, but some custom HTML inside the 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. It is the black magic that HTML helpers do to get this job done that I haven't been able to figure out yet. So I'll leave this to later or to someone else, but I think this question is related to this:

custom htmlhelper with validation support

+2


source


In your autocomplete change event, assign this value to your hidden field.



0


source







All Articles