'Custom validation for a custom field on registration form on woocommerce

I need to validate a text input on the woocommerce registration form. The input must contain codes only from a database table. So let's say i have multiple rows on the table named "secret_codes" on the "code" column. I need to validate this input, if the code typed by an user is not from the rows form the database table, then an error appears and the form is not submitter, and no user is created.

something like these, but this is just a validation for an empy field, i need to be the exact value of one of the multiple rows in database table

function wooc_validate_extra_register_fields( $username, $email, $validation_errors ) {

    if ( isset( $_POST['first_name'] ) && empty( $_POST['first_name'] ) ) {
        $validation_errors->add( 'first_name_error', __( '<strong>Error</strong>: First Name is required!.', 'woocommerce' ) );
    }

    if ( isset( $_POST['last_name'] ) && empty( $_POST['last_name'] )  ) {
        $validation_errors->add( 'last_name_error', __( '<strong>Error</strong>: Last Name is required!.', 'woocommerce' ) );
    }
}

add_action( 'woocommerce_register_post', 'wooc_validate_extra_register_fields', 10, 3 );


Solution 1:[1]

You need to use $wpdb object to interact with wordpress database

You added the custom fields to front end, But you have to make some operations in save db fucntions:

function woocom_save_extra_register_fields($customer_id) {
 global $wpdb 

 if (isset($_POST['first_name']) && isset($_POST['last_name'])) {

 $res = $wpdb->query($wpdb->prepare("SELECT codes FROM $wpdb->short_codes WHERE 
codes=%d",$code));



if(count($res) > 0)
   {
     // code for valid user
   }

update_user_meta($customer_id, ‘first_name’);
sanitize_text_field($_POST['first_name']));
update_user_meta($customer_id, 'last_name'); 
sanitize_text_field($_POST['last_name']));

}

}

refer to https://developer.wordpress.org/reference/classes/wpdb/

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mohamed.nabil