I was wondering how to set an error message from js to Drupal ? something like


but in Drupal object in js

jQuery(document).ready (function(){

is this even possible?

4 Answers 4


The drupal_set_message() works by storing the messages into a session and displays when the page is reloaded.

If you want to show an error message through javascript, include js in your module (if working with some module).

You could simply append an error message on some event

    jQuery(document).ready (function(){
    jQuery(".error-message").append('<div class="messages error">Error message to be displayed</div>');

It will simply display an error message. You can apply further Js code as desired output.

  • yes that would suffice thank you :D actually i would like to go a bit further and have a ready function to set a message so i could use jquery and build a function that will delete and /or show a message ;)
    – aimiliano
    Jul 24, 2014 at 12:04
  • However in this case you hardcode the wrapper: What is the general error message div wrapper changes? You have to edit it at each places.
    – ssibal
    Nov 1, 2018 at 8:48

If you want to attach the message above the form you can do

jQuery("form").prepend('<div class="messages error">Error message to be displayed</div>');

Based on Adrian Cid Almaguer answer.


In Drupal 8 and later you can use core/drupal.message library for that.

Add the core/drupal.message as a dependency for your custom library.

To add a message using Drupal messages API you need:

const message = new Drupal.Message();
message.add('Please enter your name', {type: 'error'});
message.add('Something happen', {type: 'warning'});

To clear the messages use the message.clear();


you can use jQuery Validate plugin. it populates the HTML errors containers with proper messages.



Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.