0

I want to validate a form with the build-in functionality of asp.net core mvc, but the validation message should be nicely displayed with the data-error attribute from materializecss. To make this work, i need the message in the View as String.

In the View I added the jquery.validate.js and jquery.validate.unobtrusive.js. Both are loaded correctly. The form will be submitted with jquery ajax. To make the validation work, the submit-button does an AJAX call and prevents the submit action.

Normally i would write something like that in the View (which works):

@Html.TextBoxFor(model => model.Email, "", new { @id = "EMail", @type = "email", @class = "validate" })
@Html.LabelFor("E-Mail Address", null, new { @for = "EMail"})
@Html.ValidationMessageFor(model => model.Email)

But I want to set the validation message to the data-error HTML-attribute to style it like materializecss.

So I tried:

@Html.TextBoxFor(model => model.Email, "", new { @id = "EMail", @type = "email", @class = "validate" })
@Html.LabelFor("E-Mail Address", null, new { @for = "EMail", data_error = Html.ValidationMessageFor(model => model.Email) })

wich always gives me "Microsoft.AspNetCore.Mvc.Rendering.TagBuilder" as error message.

How can I set the validation message from the ViewModel to the data-error html-attribute in the @Html.LabelForModule method?

To clearify, this is my ViewModel:

public class UserViewModel
{
    [Required(ErrorMessage = "The FirstName address is required")]
    public string FirstName { get; set; }

    [Required(ErrorMessage = "The LastName address is required")]
    public string LastName { get; set; }

    [Required(ErrorMessage = "The Email address is required")]
    [EmailAddress(ErrorMessage = "Invalid Email Address")]
    public string Email { get; set; }
}
Gehtnet
  • 391
  • 6
  • 22
  • I am not sure this is what you are looking for, but I had a similar (i believe) question a while back. Here is the answer I got. https://stackoverflow.com/a/41168951/5874935 – Travis Tubbs Jul 20 '17 at 17:22

1 Answers1

0

You can display error message like MaterializeCSS by css and without data-error attribute.

HTML inputs:

<div class="input-field col s12">
    @Html.TextBoxFor(model => model.Email, "", new { @id = "EMail", @type = "email",     
    @class = "validate" })
    @Html.LabelFor("E-Mail Address", null, new { @for = "EMail"})
    @Html.ValidationMessageFor(model => model.Email)
</div>

css:

.field-validation-error span {
    color: inherit;
    display: block;
    position: absolute;
    right: 0;
    top: 100%;
    transition: .2s opacity ease-out, .2s color ease-out;
    -webkit-transition: .2s opacity ease-out, .2s color ease-out;
}

Css Validation

Mohsen Esmailpour
  • 10,476
  • 2
  • 39
  • 64