babsevensix babsevensix - 3 months ago 17
C# Question

Show asterisk with NotEmpty using Fluentvalidation

I want to show on Asp.Net MVC 4 web page a

label
with asterisk when property have
NotEmpty
rule.

Answer

Just add this function to your common script functions and run on load

$(document).ready(function(){
     setRequired();  
 });

 function setRequired() {
    var $form = $('form');
    $('form').find("[data-val-required]").each(function (index) {
        var $input = $(this); 
        var requiredAsterisk = "<span class=\"required\">*</span>";
        var id = $input.attr('id');
        var $label = $form.find("label[for='" + id + "']");
        if ($label.length > 0) {
            var html = $label.html() + "";
            if (html.indexOf(requiredAsterisk) <= 0) $label.html(html + requiredAsterisk);
        }
    });
};

What this does it , it adds asterisk to labels of required fields. You can easily change it to add it right next to input fields.

Another thing to note is I use css class = required, so remember to add the color:red for this css class.