0

We're currently making a project using ASP.NET MVC 4. Because I am working with the select2 plugin, validation isn't all that easy. The standard message for required items in jQuery validation is "This field is required!". After hours and hours of searching I've found how to change this message. Below you can see how I change it, this is working (message gets displayed using @Html.ValidationMessageFor(--property of my ViewModel--). It's pretty weird this works, because I can't get the actual Data Annotation message to display, but the jQuery message does luckily.

$.validator.messages = {
    required: "@Resources.Question_MinOnePol"
};

This works, problem is I now get the same message for each required field. I would like to get a different custom message based on id or maybe class.

I have no idea how to do this... Hope you can give me tips on how to achieve this.

Extra's:

Example of a select list using select2:

<select name="PoliticianIds" id="polDrop" multiple style="width: 700px" required class="select2pol required">
            @foreach (var par in ((List<Party>)ViewBag.Parties))
            {
                <optgroup label="@par.Name (@par.FullName)">

                    @foreach (var pol in ((List<Politician>)par.Politicians))
                    {
                        @(ViewBag.CurrPol = pol)
                        <option value="@pol.UserId">@pol.FirstName @pol.LastName (@pol.Party.Name)</option>
                    }

                </optgroup>
            }
        </select>
        @Html.ValidationMessageFor(model => model.PoliticianIds)

Script to make it a select2 list:

jQuery('#polDrop').select2({
        placeholder: "Selecteer een politicus...",
        maximumSelectionSize: 5,
        formatResult: format2,
        formatSelection: format2,
        escapeMarkup: function(m) {
            return m;
        }
    });

My ViewModel for anyone interested:

public class CreateQuestionModel
{
    public Question Question { get; set; }
    [Required(ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "Question_MinOnePol")]
    public List<int> PoliticianIds { get; set; }
    public List<int> TopicIds { get; set; }
}

I would be glad to provide any additional details if needed.

E. V. d. B.
  • 815
  • 2
  • 13
  • 30

1 Answers1

0

Found the answer in the following StackOverflow thread:

jQuery validation: change default error message

I'm sorry, didn't find it before!

How I solved it:

$('#polDrop').rules("add", {
        messages: {
            required: "Politician is required!"
        }
    });

    $('#topDrop').rules("add", {
        messages: {
            required: "Topic is required!"
        }
    });

The id's I call in the jQuery are of course the id's of my <select>s!

Community
  • 1
  • 1
E. V. d. B.
  • 815
  • 2
  • 13
  • 30