How do I use form_set_error() the right way? In my Drupal 7 module, I have a form and its validation handlers. I call my form from a field.tpl.php with print render(drupal_get_form('my_form')); it works as expected.

The problem is in case of wrong input value.

It requires two incorrect submissions before displaying the error message: The first time, there is red border around my wrong input, and the second time, the error message is displayed (with the red border).

So, what's the right way to use form_set_error()?
You should be looking at form_set_error instead

if you have an element like this:

function my_custom_module_form() {
  $form = array();
  $form['my_element'] = array(
    '#type' =&gt; 'textfield',
    '#title' =&gt; 'My Text field',
    '#default_value' =&gt; 'Some default text.',
  );
  return $form;
}


in your validation callback function do this if you find that the values in $form_state['values'] aren't valid

function my_custom_module_form_validate($form, &amp;$form_state) {
  // Do some checking on $form_state['values'], if you don't like it.
  form_set_error('my_element', 'This is the error message that will be displayed.');
}