简体   繁体   中英

Show validation messages below the element with jquery unobtrusive in asp.net mvc3

I need to show the validation messages below the element.

I have tried adding the message like:

[Required(ErrorMessage = "<br /> UserName is required")]
public string UserName { get; set; }

But the above required message is rendered as (where the validation messages is encoded):

<input type="text" value="" tabindex="1" style="height:auto; width:280px;" size="40" name="UserName" maxlength="15" id="UserName" data-val-required="&amp;lt;br /&amp;gt; UserName is required" data-val="true" class="textfield">

验证信息

If i remove the <br/> from the message of the Model, the validation message shows in two lines. Also i have tried adding the validation as below, but the validation message is not overriden as in the below validate method (overriding from "UserName is required" to "Enter username"):

$('#userSignInform').validate({
    rules:
        {
            UserName: { required: true },
            Password: { required: true }
        },
    messages:
        {
            UserName: { required: "Enter Username" },
            Password: { required: "Enter the Password" }
        },
    errorPlacement: function (error, element)
        {
            error.appendTo(element.parent("td").next("td"));
        }
});

Whats the workaround need to be done to show the validation messages below the element and to override the model message with the jquery validate method?

Validation message markup is generated as:

<span class="field-validation-error" data-valmsg-for="UserName" data-valmsg-replace="true">
     <span for="UserName" generated="true" class="">UserName is required</span>
</span>

As you see, it has got class field-validation-error . Just add up simple css to display validation message on new line

.field-validation-error {
    display: block;
}

And the validation messages will be displayed of the second line.

If you want this placement applied only to specific messages, just change class selector to be more specific.

Just add <br/> in html.

Eg:

@Html.LabelFor(m => m.UserName, "User Name 1")
@Html.TextBoxFor(m => m.UserName)<br />
@Html.ValidationMessageFor(m => m.UserName)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM