Skip to content

Instantly share code, notes, and snippets.

@swoboda
Last active March 17, 2023 08:01
Show Gist options
  • Save swoboda/446ded1dad928c9baf436140e5e9a537 to your computer and use it in GitHub Desktop.
Save swoboda/446ded1dad928c9baf436140e5e9a537 to your computer and use it in GitHub Desktop.
Flexible Checkout Fields - Walidacja polskiego numeru NIP
<?php
// NIE kopiuj powyższego tagu otwierającego php
/**
* Funkcja do walidacji polskiego numeru NIP
*
*/
function wpdesk_fcf_validate_nip( $field_label, $value ) {
$valid = false;
$weights = array( 6, 5, 7, 2, 3, 4, 5, 6, 7 );
$nip = preg_replace( '/^PL/', '', $value );
if ( strlen( $nip ) == 10 && is_numeric( $nip ) ) {
$sum = 0;
for( $i = 0; $i < 9; $i++ )
$sum += $nip[$i] * $weights[$i];
$valid = ( $sum % 11 ) == $nip[9];
} elseif ( strlen( $nip ) == 0 ) {
$valid = true;
}
if ( $valid === false ) {
wc_add_notice( sprintf( __( 'Pole %s jest wypełnione niepoprawnie. Wpisz polski numer NIP bez spacji i myślników.', 'wpdesk' ), '<strong>' . $field_label . '</strong>' ), 'error' );
}
}
add_filter( 'flexible_checkout_fields_custom_validation', 'wpdesk_fcf_custom_validation_nip' );
/**
* Własna walidacja polskiego numeru NIP
*
*/
function wpdesk_fcf_custom_validation_nip( $custom_validation ) {
$custom_validation['nip'] = array(
'label' => __( 'Polski NIP', 'wpdesk' ),
'callback' => 'wpdesk_fcf_validate_nip'
);
return $custom_validation;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment