How to check that any error message is diplaying in visualforce page

I wonder if you can use the css class errorMsg of the error block:

enter image description here

If this class exists on the page - there is an error:

<apex:page>
<script>
function checkIt(){
    if (jQuery('.errorMsg').length > 0){
        // Error exists
        alert('There is an error on the page!');
    }
    else{
        alert('No errors!');
    }
}
</script>

<apex:commandButton reRender="none" oncomplete="checkIt();" value="Click me"/>

</apex:page>

Well, you can definitely call ApexPages.hasMessages() from your apex. There's even a version that lets you specify the severity (WARNING, ERROR, FATAL, INFO) that you're looking for.

http://www.salesforce.com/us/developer/docs/pages/Content/apex_System_ApexPages_instance_methods.htm

To use this in your javascript, you could make a controller property or method that returns this result, and then simply access it via mergefield. So for example, you might define a controller method:

public Boolean ErrorsPresent(){
    return ApexPages.hasMessages(ApexPages.Severity.ERROR);
}

Then your Javascript might looks like

if({!ErrorsPresent}){
    alert('Woah there, buddy! Looks like there may be a problem');
}

Pages with a StandardController expose a property:

{!Messages}

Without the need for a custom controller or extensions, can do things like:

<apex:pageBlock rendered="{!ISNULL(Messages)}">
    <!-- detailed troubleshooting instructions -->
</apex:pageBlock>

<apex:pageBlock rendered="{!NOT(ISNULL(Messages))}">
    <!-- normal page functionality -->
</apex:pageBlock>

Tags:

Visualforce