Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a field required on razor view?

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?

like image 452
M. ELOUALI Avatar asked Mar 27 '12 11:03

M. ELOUALI


1 Answers

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');
like image 109
Darin Dimitrov Avatar answered Sep 28 '22 17:09

Darin Dimitrov