diff --git a/src/wp-admin/includes/user.php b/src/wp-admin/includes/user.php
index 269d64fb26..30f29a42ba 100644
--- a/src/wp-admin/includes/user.php
+++ b/src/wp-admin/includes/user.php
@@ -45,10 +45,10 @@ function edit_user( $user_id = 0 ) {
 
 	$pass1 = $pass2 = '';
 	if ( isset( $_POST['pass1'] ) ) {
-		$pass1 = $_POST['pass1'];
+		$pass1 = trim( $_POST['pass1'] );
 	}
 	if ( isset( $_POST['pass2'] ) ) {
-		$pass2 = $_POST['pass2'];
+		$pass2 = trim( $_POST['pass2'] );
 	}
 
 	if ( isset( $_POST['role'] ) && current_user_can( 'edit_users' ) ) {
diff --git a/tests/phpunit/tests/user.php b/tests/phpunit/tests/user.php
index bcfa036d37..e6c7c5ccb6 100644
--- a/tests/phpunit/tests/user.php
+++ b/tests/phpunit/tests/user.php
@@ -1362,6 +1362,7 @@ class Tests_User extends WP_UnitTestCase {
 	 * Checks that calling edit_user() with no password returns an error when adding, and doesn't when updating.
 	 *
 	 * @ticket 35715
+	 * @ticket 42766
 	 */
 	function test_edit_user_blank_pw() {
 		$_POST                 = $_GET = $_REQUEST = array();
@@ -1398,6 +1399,17 @@ class Tests_User extends WP_UnitTestCase {
 		$this->assertInternalType( 'int', $user_id );
 		$this->assertEquals( 'nickname_updated', $user->nickname );
 
+		// Check not to change an old password if a new password contains only spaces. Ticket #42766
+		$user           = get_user_by( 'ID', $user_id );
+		$old_pass       = $user->user_pass;
+		$_POST['pass1'] = $_POST['pass2'] = '  ';
+
+		$user_id = edit_user( $user_id );
+		$user    = get_user_by( 'ID', $user_id );
+
+		$this->assertInternalType( 'int', $user_id );
+		$this->assertEquals( $old_pass, $user->user_pass );
+
 		// Check updating user with missing second password.
 		$_POST['nickname'] = 'nickname_updated2';
 		$_POST['pass1']    = 'blank_pass2';
