I want to add the "data-val-required" and "data-val" attributes to an @html.textbox or an @Html.EditorFor element. Is it possible without rewriting the view?
Normally you should not rewrite the view to achieve that. You should decorate your view model properties with the corresponding validation attributes. For example:
[Required]
public string Foo { get; set; }
Then the Html helpers will generate the correct markup. But if for some weird reason you cannot modify this code you could use javascript in order to add those attributes manually:
$(function() {
$('#id_of_the_field').attr('data-val-required', 'true');
});
Once you add those attributes you need to reparse the validation rules of the form containing those input fields for your changes to take effect:
$('form').removeData('validator');
$('form').removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse('body');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With