Skip to main content

AddToAny

Share/Save

How to do Numeric Validation in Drupal Webforms

I spent a lot of time to figure out How to restrict only numeric data in drupal webforms. To my surprise drupal does'nt provide such functionality. But we can achieve it through Additional Validation in Webform Advanced Settings.

Just write this PHP code in additional validation.

  $mobile_no = $form_values['submitted_tree']['mobile_no'];
  if (strlen(trim($mobile_no)) > 0){
    if (!is_numeric($mobile_no)) {
      form_set_error('submitted][mobile_no', t('Mobile No. must be Numeric'));
    }
  }

Replace mobile_no with your "Field Key" of the component you want to validate

Thanks

Thanks for this great information. You save me a lot of time.

@Nikhil

My pleasure.

Thanks. Can you provide more

Thanks. Can you provide more information. If you can attach some snapshots, it would be great

The field module has a

The field module has a function for this: _element_validate_number, so you can do:

$form['my_numeric_field'] = array(
    '#type' => 'textfield',
    '#title' => t('Number'),
    '#description' => t('This is a numeric field'),
    '#default_value' => 0,
    '#element_validate' => '_element_validate_number',
);

Sorry, I made a mistake, the

Sorry, I made a mistake,
the validate functions should be in an array, so the code looks like:

$form['my_numeric_field'] = array(
    '#type' => 'textfield',
    '#title' => t('Number'),
    '#description' => t('This is a numeric field'),
    '#default_value' => 0,
    '#element_validate' => array('_element_validate_number'),
);

How do I implement this?

This is awesome Jelle,

I am a noob and wonder how I can implement this into a form. Where does the code go?

Thanks a lot

Thanks a lot for this code snippet! :)

than ks a lot

It solve my problem thanks a lot sir

Post new comment

The content of this field is kept private and will not be shown publicly. If you have a Gravatar account, used to display your avatar.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <p> <span> <div> <h1> <h2> <h3> <h4> <h5> <h6> <img> <map> <area> <hr><br> <br /> <ul> <ol> <li> <dl> <dt> <dd> <table> <tr> <td> <em> <b> <u> <i> <strong><font> <del> <ins> <sub> <sup> <quote> <blockquote> <pre> <address> <code> <cite> <embed> <object> <param> <strike> <caption>
  • You can enable syntax highlighting of source code with the following tags: <c>, <cpp>, <csharp>, <drupal5>, <drupal6>, <java>, <javascript>, <mysql>, <php>, <python>, <ruby>, <sql>, <tsql>, <vbnet>, <xml>. Beside the tag style "<foo>" it is also possible to use "[foo]". PHP source code can also be enclosed in <?php ... ?> or <% ... %>.
  • Lines and paragraphs break automatically.

More information about formatting options