Search code examples
regexvalidationwoocommerceregistration

Need to Validate a couple of fields using code.in functions.php


My first post here! I am setting up a woocommerce registration (the one which appears on the checkout page). I am using a plugin by Extendons: WooCommerce Custom Registration Fields Plugin which has everything but unfortunately I can't set the vaildation of some fields. Basically I have fields for registration numbers for doctors and nurse. The Doctor number needs to be validated (by regex probably) only if it is exactly 7 numbers (any numbers). The Nurses have this exact format: 00(Letter)0000(letter): o = any letter. The different registration number fields appear conditionally on whether Doctor or Nurse is selected. The plugin achieves all this no problem though.

I would be graeful if anyone could provide some insight or at least point me in the right direction as my php knowledge is limited. Thanks!


Solution

  • If you are trying to match only numbers that are 7 digits long, just add a trailing anchor using $, like this:

    ^(\d{7})$
    

    That will match any number that is exactly 7 digits long.

    On PHP

    <?php
    
    $re = "/^(\d{7})$/";
    $test_input_doctor = "1234567"; // valid scenario
    //$test_input_doctor = "12345678"; //invalid scenario, you can test it as well by just commenting out this line
    
    if (preg_match($re, $test_input_doctor))
    {
        echo "valid doctor id";
    }
    else
    {
        echo "invalid doctor id";
    }
    ?>