Pete
Pete

Reputation: 58422

Change mvc form validation error messages

I am trying to change the data-val-required attributes of my form fields so that I get a generic "required" appear. Now I know that I can do this using the following:

@Html.TextBoxFor(model => model.Name, new { data_val_required ="required" })

But I don't want to "hard code" it into the template like that, I would prefer the model to use the required attribute set on it and then override it through js using something like this:

$('input, select, textarea').each(function () {
    var element = $(this);
    if (element.data('val-required')) {
        element.data('val-required', 'required');
    }
});

I've run this on document ready and checked the data attributes have changed (which they have) but apparently this is happening too late for the validation to take note of it. So I need to know when MVC binds it's form validation so I can run this before or how to change the error messages clientside only.

I've looked through the source of the page and just can't see where the validate gets instantiated.

For those saying change the required attribute or do it server side, I don't want to do this as if I have js disabled I display a validation summary at the top of the form which will be pretty useless if they all just say required. That is why I want to do this client side only

enter image description here

Upvotes: 0

Views: 6671

Answers (3)

Hunter Nelson
Hunter Nelson

Reputation: 1985

I think you can achieve this with data annotations. Just mark the model items as

[Required]  

If you want to override the error message just do this

[Required(ErrorMessage = "Name is required")]

See this post: Error messages for model validation using data annotations

Upvotes: 2

Mathew Thompson
Mathew Thompson

Reputation: 56429

You really don't want to be doing this in the JavaScript and manipulating attributes, this is perfectly achievable in Razor.

Simply have your ValidationSummary not exclude individual property errors:

@Html.ValidationSummary(false)

And then remove all your ValidationMessageFors for all the fields.

Upvotes: 1

Pete
Pete

Reputation: 58422

For those of you interested in the solution, the following will reset the validation messages:

(function () {
    $('input, select, textarea').each(function () {
        var element = $(this);
        if (element.data('val-required')) {
            element.attr('data-val-required', 'Required'); // please note this has to be the attr not data
        }
    });

    form = $('form');
    form.removeData("validator").removeData("unobtrusiveValidation");
    $.validator.unobtrusive.parse(form);
});

Upvotes: 2

Related Questions