Skip to content

Instantly share code, notes, and snippets.

@BruceMcKinnon
Created December 11, 2023 21:04
Show Gist options
  • Save BruceMcKinnon/e50f920912564200f6fffd52b6328a33 to your computer and use it in GitHub Desktop.
Save BruceMcKinnon/e50f920912564200f6fffd52b6328a33 to your computer and use it in GitHub Desktop.
Ninja Forms Australian Phone number validation
//
// Hook the Ninja forms before submitting
//
add_filter( 'ninja_forms_submit_data', 'my_ninja_forms_submit_data' );
//
// This function hooks the Ninja submission step
// Thanks to https://stackoverflow.com/questions/61440656/ninja-forms-server-side-validation-not-working
//
function my_ninja_forms_submit_data( $form_data ) {
$form_settings = $form_data[ 'settings' ]; // Form settings.
// Contact form is ID #1
if ($form_data['id'] == '1') {
// Target key field.
// With Ninja dev mode enabled, open the phone field settings and set Administration > Field Key and set to this value
$target_key = 'phone_au';
foreach( $form_data[ 'fields' ] as $field ) {
if( $target_key == $field[ 'key' ] ) {
// Now pass the phone field value to the AU phone number validator
if ( ! bl_match_aus_phone($field['value']) ) {
$form_data['errors']['fields'][$field['id']] = "You must provide a valid AU phone number.";
}
}
}
}
return $form_data;
}
//
// This is my generic AU phone format validator.
//
function bl_match_aus_phone ( $number ) {
try {
// Get rid of any non-numerics
$number = preg_replace('/[^0-9]/s', '', $number);
if (preg_match('/^0(2|3|4|7|8)?\d{8}$/', $number) || preg_match('/^61(2|3|4|7|8)?\d{8}$/', $number) ||
preg_match('/^1(3|8)00\d{6}$/', $number) || preg_match('/^13\d{4}$/', $number) ||
preg_match('/^611(3|8)00\d{6}$/', $number) || preg_match('/^6113\d{4}$/', $number) ) {
$result = true;
} else {
$result = false;
}
} catch (Exception $e) {
$result = false;
}
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment