2

I am following this tutorial to display validation errors in jqueryui tooltip. The validation works fine, but I am unable to display the correct error messages as the correct attributes can not be conditionally linked to the tooltip, as per my example below:

$(document).tooltip({
        items: ".input-validation-error",
        content: function () {

            //debugger;
            return $(this).attr('data-val-required');
        }
    });

Only the required field error message will be displayed by this logic, is there a way to extend this logic by tapping into the validation results (for remote and compare type validations), or have I hit a dead-end?

2 Answers 2

4

Since the content() function is called on demand, you can supply whatever text you need based on the attributes of this which is the element in question.

You need to inspect the element and return the text for the validation error that occurred. Something like:

$(document).tooltip({
    items: ".input-validation-error",
    content: function () {

        //debugger;
        return $(this).attr('data-val-required') || 
               $(this).attr('data-val-date') ||
               $(this).attr('data-val-number'); // etc etc
    }
});

This will return the data validation attribute that is populated with an error message.

Sign up to request clarification or add additional context in comments.

2 Comments

I am still unable to get this to work correctly, as per your suggestion is modified the return as per below: return $(this).attr('data-val-remote') || $(this).attr('data-val-required') || $(this).attr('data-val-equalto'); the text message appears to default to the first option.
Well, I am just typing into a browser and can't run your code. The concept is the important thing despite any syntax problems. You can inspect the element and return the error text you want to show.
4

Using the tutorial referenced in the original question, change line 4 from:

@{ Html.ValidateFor(m => m.UserName); }

to:

@Html.ValidationMessageFor(m => m.Username, null, new {style="visibility:hidden"})

Then, modify the content function as follows:

$(document).tooltip({
    items: ".input-validation-error",
    content: function () {
        return $("[data-valmsg-for='" + $(this).attr('id') + "']").text();
    }
});

Essentially, we don't want the original ValidationMessageFor span displaying (visibility=hidden). We're simply using it as the container for the tooltip.

1 Comment

I used style="display:none" instead of visibility property because the hidden element occupies space in the form even if its visibility is hidden while with display none it doesn't occupy space

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.