ASP.NET MVC Required Field Indicator

Deadly 提交于 2019-11-28 23:57:14

Should be able to do this with CSS since MVC3 adds in those custom attributes to the element:

 <input data-val="true" data-val-required="The Username field is required." id="Username" name="Username" type="text" value="" />

You could key off the data-val-required in CSS like so:

input[data-val-required] { background:red } or set a background image of an asterisk etc.

I did that way because my required fields must be dynamic (defined in a configuration file)

Add at the end of your View:

    <script type="text/javascript">
        $('input[type=text]').each(function () {
            var req = $(this).attr('data-val-required');
            if (undefined != req) {
                var label = $('label[for="' + $(this).attr('id') + '"]');
                var text = label.text();
                if (text.length > 0) {
                    label.append('<span style="color:red"> *</span>');
                }
            }
        });
    </script>

Here is one that will attach a red asterisk to the right side of anything with the attribute 'data-val-required'.

<script type="text/javascript">
    $('[data-val-required]').after('<span style="color:red; font-size: 20px; vertical-align: middle;"> *</span>');
</script>

I modified Renato Saito's answer to include more field types (all types of input and select lists) and use the jQuery namespace instead of the generic $. Here is my revision:

<script type="text/javascript">
// add indicator to required fields
jQuery('input,select').each(function () {
    var req = jQuery(this).attr('data-val-required');
    if (undefined != req) {
        var label = jQuery('label[for="' + jQuery(this).attr('id') + '"]');
        var text = label.text();
        if (text.length > 0) {
            label.append('<span style="color:red"> *</span>');
        }
    }
});
</script>

Adding html attribute is not enough. This will only cause javascript validation error. If you want to indicate that the field is required you'd probaly want to add an asterisk to it. You can do it by means of extenssion method of HtmlHelper. You can find a thorough explanation here

Indicating required field in MVC application

Santokh SIngh

A Small Modification Is Done From My Side. Actually I had primary keys (Identity Columns in DB). That I did no want to highlight. So I Used Below Code Snippet to select only input[type=text] fields that has required attribute in annotation.

$("[data-val-required]").not(":hidden").not(":radio").not(":checkbox").after('<span style="color:red;max-width:10px;min-height:30px;">*</span>');
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!