Server-side Validation of Edit Profile Form

BuddyPress + ProfilePress = Awesome

In case you didn’t know, ProfilePress ship with a front-end edit profile form and My Account page where registered users of your membership site can edit their profile information or account details.

In this tutorial, I will show us how to validate edit profile form fields on the server side.

Note: all code in this post should go into your active theme’s functions.php file a site-specific plugin.

Tutorial Proper

All server-side validation should be done in ppress_edit_profile_validation filter.

For example, the code snippet below will cause the edit profile form not to update the user information if the password field is empty.


add_filter( 'ppress_edit_profile_validation', function ( $wp_error ) {
	if ( isset( $_POST['eup_password'] ) && empty( $_POST['eup_password'] ) ) {
		$wp_error = new WP_Error( 'empty_password', 'Password cannot be empty.' );
	}

	return $wp_error;
} );

We can go a step further and cause the form not to update if the user password is less than five(5).


add_filter( 'ppress_edit_profile_validation', function ( $wp_error ) {
	if ( isset( $_POST['eup_password'] ) && strlen( $_POST['eup_password'] ) < 5 ) {
		$wp_error = new WP_Error( 'password_length', 'Password length must be greater than 5' );
	}

	return $wp_error;
} );

Validating custom fields is pretty much the same as the examples above.

For example, say you have a Province custom field with the field key province and you want to ensure the field is not empty.


add_filter( 'ppress_edit_profile_validation', function ( $wp_error ) {
	if ( isset( $_POST['province'] ) && empty( $_POST['province'] ) ) {
		$wp_error = new WP_Error( 'empty_field', 'Province field cannot be left empty.' );
	}

	return $wp_error;
} );

A custom field that is a multi-select dropdown can be quite tricky because its value type is an array and not a string. Let’s see some examples.

Assuming you have a car brand multi-select custom field with key car_brand with five options and you insist user must select at leave the field empty, see the code snippet below.


add_filter( 'ppress_edit_profile_validation', function ( $wp_error ) {

	if ( is_null( $_POST['car_brand'] ) ) {
		$wp_error = new WP_Error( 'field_empty', 'Car brand field cannot be left empty' );
	}

	return $wp_error;
} );

We can also go a step further and ensure that at least two options are selected.


add_filter( 'ppress_edit_profile_validation', function ( $wp_error ) {

	if ( isset( $_POST['car_brand'] ) && count( $_POST['car_brand'] ) < 2 ) {
		$wp_error = new WP_Error( 'options_left', 'At least two car brands must be selected.' );
	}

	return $wp_error;
} );

If you have any question or not clear about anything in the post, let us know in the comments.