0

i have set up a few validation rules and i have a VFpage using this object. I am able to capture the validation exception and display it on the VF page. The issue is that it shows message as

   " Upsert Failed : First exception on row 0: first error;

     FIELD_CUSTOM_VALIDATION_EXCEPTION Quantity cannot be empty

Is there a way i can just capture the error message in validation Rule "Quantity cannot be empty" ?

Thanks

3 Answers 3

6

Unfortunately, Ralph's post is not 100% correct (see Prady's comment that it won't work for top-of-page validation errors), so I write this answer to clearify.

  1. Add <apex:pageMessages/> tag to your page
  2. Enclose your DML statement with try catch like this:
try{

update account; //or anything else

} catch(System.DmlException e) {
   ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, e.getDmlMessage(0)));
}

This will print the first DML error that statement caused which is usually what you want. You can also try e.getMessage() but this will show additional information (like Update failed. First exception on row 0 with id 001L000000QgmomIAB; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION etc.) which is not user friendly. The advantage of e.getDmlMessage is that it prints only the validation rule when the error is caused by validation rule.

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

2 Comments

ApexPages.Message and not ApexPage.Message but otherwise this fixed my issue, thanks.
Thanks for your comment, fixed.
4

Visualforce can do this for you

  1. Add the <apex:pageMessages/> tag to your page. (This is the container that displays any error messages if present)
  2. Surround your DML call with try {} catch(DMLException e) {} (When you catch the exception you won't get redirected to the error pages, but salesforce will automatically create a "PageMessage" for the validation failure.

1 Comment

It doesnt seem to catch if we have the validation rule error message to show up on top of page. It works if its set the field
0

If you use this:

ApexPages.addMessages(e);

instead the user will receive all validation messages at the same time instead of having to work through each one, one at a time.

Comments

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.