Have a custom field on Contact called as 'Employee ID #'. We want to restrict user/staff from submitting the form from adding more than 6 digits. How to add validation on custom field to accept up-to 6 digits only? i.e between 0 to 999999.

3 Answers 3


There are many ways you can achieve this

  1. Implementing hook_civicrm_validateForm() hook via extension/module/plugin to add php code .


function MYMODULE_civicrm_validateForm($formName, &$fields, &$files, &$form, &$errors) {
  // 12 is the custom field id
  // inspect on form to get the exact field name
  if (!empty($fields['custom_12'])) {
    preg_match("/^[0-9]{0,6}$/", $fields['custom_12'], $matches);
    if (empty($matches)) {
      $errors['custom_12'] = ts('Error message.');
  1. Implementing hook_civicrm_buildForm() hook to add js via extension/module/plugin or from theme function


function MYMODULE_civicrm_buildForm($formName, &$form) {
  // Replace the FORM_NAME with Form name
  if ($formName == 'FORM_NAME') {
      "CRM.$(function($) {
        // on custom field blur or change OR submit button hit
        // Check if the value in text is upto 6 digit using match()
        // display error using CRM.alert(ts('Error message'), ts('Error'));
  1. You can add HTML5 pattern to do the validation. Civi provides attributes to be added into Custom field, however this is not visible through GUI, you can use mysql query or api3 or api4 explorer to add.

Mysql code:

-- Add attribute for custom field id 12
UPDATE civicrm_custom_field SET attributes = ' pattern="^[0-9]{0,6}$" ' WHERE id = 12;


enter image description here


enter image description here

  • Wow you went all out on this one. Cool.
    – Demerit
    Dec 22, 2021 at 23:16

You could make the field a dropdown list or autocomplete with a million option choices (ha ha! I'm joking. Partly - it would technically work...)

  • 3
    a good answer for this crazy xmas period
    – petednz - fuzion
    Dec 23, 2021 at 4:32

If this was Drupal and you were happy doing this via a Webform then webform_validation might be your friend - and could potentially enforce 'unique' too if that mattered

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.