:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(signup): trim and split full name so first_name is never blank (#79431)
Eleftheria Trivyzaki26635a3fd9dd
diff --git a/frontend/src/lib/utils/strings.test.ts b/frontend/src/lib/utils/strings.test.tsindex 71edf6c2ec11..8ca1f4da4498 100644--- a/frontend/src/lib/utils/strings.test.ts+++ b/frontend/src/lib/utils/strings.test.ts@@ -5,6 +5,7 @@ import {identifierToHuman,midEllipsis,pluralize,+ splitFullName,wordPluralize,} from 'lib/utils/strings'@@ -107,4 +108,28 @@ describe('strings utils', () => {expect(ensureStringIsNotBlank(' happy boy ')).toEqual(' happy boy ')})})++ describe('splitFullName()', () => {+ it('splits a simple two-part name', () => {+ expect(splitFullName('John Smith')).toEqual({ first_name: 'John', last_name: 'Smith' })+ })+ it('returns no last name for a single name', () => {+ expect(splitFullName('John')).toEqual({ first_name: 'John', last_name: undefined })+ })+ it('trims surrounding whitespace before splitting', () => {+ expect(splitFullName(' John')).toEqual({ first_name: 'John', last_name: undefined })+ expect(splitFullName(' John Smith ')).toEqual({ first_name: 'John', last_name: 'Smith' })+ })+ it('collapses internal whitespace', () => {+ expect(splitFullName('John Smith')).toEqual({ first_name: 'John', last_name: 'Smith' })+ expect(splitFullName('\tJohn\tSmith')).toEqual({ first_name: 'John', last_name: 'Smith' })+ })+ it('keeps multi-part surnames intact', () => {+ expect(splitFullName(' Ada Van Der Berg ')).toEqual({ first_name: 'Ada', last_name: 'Van Der Berg' })+ })+ it('returns a blank first name for blank input', () => {+ expect(splitFullName('')).toEqual({ first_name: '', last_name: undefined })+ expect(splitFullName(' ')).toEqual({ first_name: '', last_name: undefined })+ })+ })})diff --git a/frontend/src/lib/utils/strings.ts b/frontend/src/lib/utils/strings.tsindex fadb05bfecc8..d7db24b29f3b 100644--- a/frontend/src/lib/utils/strings.ts+++ b/frontend/src/lib/utils/strings.ts@@ -38,6 +38,12 @@ export function fullName(props?: { first_name?: string; last_name?: string }): sreturn `${props.first_name || ''} ${props.last_name || ''}`.trim()}+/** Inverse of `fullName`: derive first/last name from a single full-name input. */+export function splitFullName(name: string): { first_name: string; last_name: string | undefined } {+ const parts = name.trim().split(/\s+/).filter(Boolean)+ return { first_name: parts[0] ?? '', last_name: parts.length > 1 ? parts.slice(1).join(' ') : undefined }+}+// trimBothEnds=false is useful when the input is slugified as the user is typing to allow them hitting space and continue typingexport function slugify(text: string,diff --git a/frontend/src/scenes/authentication/signup/signupForm/signupLogic.test.ts b/frontend/src/scenes/authentication/signup/signupForm/signupLogic.test.tsindex 4d58fe6190a9..d7796e1e4553 100644--- a/frontend/src/scenes/authentication/signup/signupForm/signupLogic.test.ts+++ b/frontend/src/scenes/authentication/signup/signupForm/signupLogic.test.ts@@ -141,3 +141,123 @@ describe('signupLogic — pending invite banner', () => {expect(logic.values.pendingInviteResent).toBe(false)})})++describe('signupLogic — name handling', () => {+ let logic: ReturnType<typeof signupLogic.build>+ let signupRequestBody: Record<string, any> | null++ const advanceToOnboardingPanel = async (): Promise<void> => {+ logic.actions.setSignupPanelEmailValue('email', '[email protected]')+ logic.actions.submitSignupPanelEmail()+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.panel).toBe(1)+ logic.actions.setSignupPanelAuthValue('password', 'Str0ng-Test-Pass!')+ logic.actions.submitSignupPanelAuth()+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.panel).toBe(2)+ }++ beforeEach(() => {+ signupRequestBody = null+ useMocks({+ post: {+ '/api/signup/precheck': () => [200, { email_exists: false, pending_invite: null }],+ // 400 rather than 201 so that the submit handler never assigns `location.href`,+ // which jsdom does not implement. The request body is captured before the response.+ '/api/signup/': async (info) => {+ signupRequestBody = (await info.request.clone().json()) as Record<string, any>+ return [400, { type: 'validation_error', code: 'error', detail: 'Mocked failure', attr: null }]+ },+ },+ })+ initKeaTests()+ router.actions.push('/signup')+ logic = signupLogic()+ logic.mount()+ })++ afterEach(() => {+ logic.unmount()+ })++ it('trims and splits the name before building the signup payload', async () => {+ await advanceToOnboardingPanel()+ logic.actions.setSignupPanelOnboardingValues({+ name: ' John van Der Berg ',+ organization_name: 'Hogflix',+ role_at_organization: 'engineer',+ referral_source: '',+ referral_source_ai_prompt: '',+ })+ logic.actions.submitSignupPanelOnboarding()+ await expectLogic(logic).toFinishAllListeners()++ expect(signupRequestBody?.first_name).toBe('John')+ expect(signupRequestBody?.last_name).toBe('van Der Berg')+ })++ it('omits a whitespace-only organization name so the backend applies its default', async () => {+ await advanceToOnboardingPanel()+ logic.actions.setSignupPanelOnboardingValues({+ name: 'John Smith',+ organization_name: ' ',+ role_at_organization: 'engineer',+ referral_source: '',+ referral_source_ai_prompt: '',+ })+ logic.actions.submitSignupPanelOnboarding()+ await expectLogic(logic).toFinishAllListeners()++ expect(signupRequestBody).not.toBeNull()+ expect(signupRequestBody).not.toHaveProperty('organization_name')+ })++ it('fails client-side validation for a whitespace-only name without issuing the POST', async () => {+ await advanceToOnboardingPanel()+ logic.actions.setSignupPanelOnboardingValues({+ name: ' ',+ organization_name: 'Hogflix',+ role_at_organization: 'engineer',+ referral_source: '',+ referral_source_ai_prompt: '',+ })+ logic.actions.submitSignupPanelOnboarding()+ await expectLogic(logic).toFinishAllListeners()++ expect(signupRequestBody).toBeNull()+ expect(logic.values.panel).toBe(2)+ })++ it('surfaces a first_name API error on the name field instead of the generic banner', async () => {+ useMocks({+ post: {+ '/api/signup/': () => [+ 400,+ {+ type: 'validation_error',+ code: 'blank',+ detail: 'This field may not be blank.',+ attr: 'first_name',+ },+ ],+ },+ })+ await advanceToOnboardingPanel()+ logic.actions.setSignupPanelOnboardingValues({+ name: 'John Smith',+ organization_name: 'Hogflix',+ role_at_organization: 'engineer',+ referral_source: '',+ referral_source_ai_prompt: '',+ })+ logic.actions.submitSignupPanelOnboarding()+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.signupPanelOnboardingManualErrors.name).toBe('This field may not be blank.')+ expect(logic.values.signupPanelOnboardingManualErrors.generic).toBeUndefined()+ // The display-level selector fields read from — the error must remain visible after the+ // failed submit (a successful submit resets showErrors and would hide it)+ expect(logic.values.signupPanelOnboardingErrors.name).toBe('This field may not be blank.')+ expect(logic.values.panel).toBe(2)+ })+})diff --git a/frontend/src/scenes/authentication/signup/signupForm/signupLogic.ts b/frontend/src/scenes/authentication/signup/signupForm/signupLogic.tsindex ebbf28224f3a..40b14626fc47 100644--- a/frontend/src/scenes/authentication/signup/signupForm/signupLogic.ts+++ b/frontend/src/scenes/authentication/signup/signupForm/signupLogic.ts@@ -11,6 +11,7 @@ import api from 'lib/api'import { ValidatedPasswordResult, validatePassword } from 'lib/components/PasswordStrength'import { CLOUD_HOSTNAMES, FEATURE_FLAGS } from 'lib/constants'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { splitFullName } from 'lib/utils/strings'import { getRelativeNextPath } from 'lib/utils/url'import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'import { getPasskeyErrorMessage, isWebAuthnCancellation } from 'scenes/settings/user/passkeys/utils'@@ -493,7 +494,7 @@ export const signupLogic = kea<signupLogicType>([referral_source_ai_prompt: '',} as SignupPanelOnboardingForm,errors: ({ name, role_at_organization }) => ({- name: !name ? 'Please enter your name' : undefined,+ name: !name?.trim() ? 'Please enter your name' : undefined,role_at_organization: !role_at_organization ? 'Please select your role in the organization' : undefined,}),submit: async (payload, breakpoint) => {@@ -503,9 +504,8 @@ export const signupLogic = kea<signupLogicType>([const signupData: Record<string, any> = {email: values.signupPanelEmail.email,- first_name: payload.name.split(' ')[0],- last_name: payload.name.split(' ')[1] || undefined,- organization_name: payload.organization_name || undefined,+ ...splitFullName(payload.name),+ organization_name: payload.organization_name?.trim() || undefined,role_at_organization: payload.role_at_organization,referral_source: payload.referral_source,referral_source_ai_prompt: payload.referral_source_ai_prompt,@@ -524,7 +524,7 @@ export const signupLogic = kea<signupLogicType>([const res = await api.create('api/signup/', signupData)- if (!payload.organization_name) {+ if (!payload.organization_name?.trim()) {posthog.capture('sign up organization name not provided')}@@ -558,6 +558,17 @@ export const signupLogic = kea<signupLogicType>([return}+ // The `name` input is split into first_name/last_name for the API — surface+ // errors on those attributes next to the field the user actually sees.+ // Must throw (not return) so kea-forms marks the submit as failed and keeps+ // showing errors — on a successful submit it hides them again.+ if (error.attr === 'first_name' || error.attr === 'last_name') {+ actions.setSignupPanelOnboardingManualErrors({+ name: String(error.detail || 'Please enter your name'),+ })+ throw e+ }+if (error.code === 'throttled') {actions.setSignupPanelOnboardingManualErrors({generic: {diff --git a/playwright/e2e/signup.spec.ts b/playwright/e2e/signup.spec.tsindex 3894535dc6db..df10aa5f68ec 100644--- a/playwright/e2e/signup.spec.ts+++ b/playwright/e2e/signup.spec.ts@@ -111,6 +111,31 @@ test.describe('Signup', () => {await expect(page).toHaveURL(/\/verify_email\/[a-zA-Z0-9_.-]*/)})+ test('Trims surrounding whitespace in the name so first_name is never blank', async ({ page }) => {+ let signupRequestBody: string | null = null++ await page.route('/api/signup/', async (route) => {+ signupRequestBody = route.request().postData()+ await route.continue()+ })++ const email = `new_user+${Math.floor(Math.random() * 10000)}@posthog.com`+ await startSignupFlow(page, email, VALID_PASSWORD)+ // A leading space used to slip through client validation and produce first_name: ""+ await page.locator('[data-attr=signup-name]').fill(' Alice Bob')+ await expect(page.locator('[data-attr=signup-name]')).toHaveValue(' Alice Bob')+ await page.locator('[data-attr=signup-role-at-organization]').click()+ await page.locator('.Popover li').filter({ hasText: 'Engineering' }).click()+ await expect(page.locator('[data-attr=signup-role-at-organization]')).toContainText('Engineering')+ await page.locator('[data-attr=signup-submit]').click()++ const parsedBody = JSON.parse(signupRequestBody!)+ expect(parsedBody.first_name).toEqual('Alice')+ expect(parsedBody.last_name).toEqual('Bob')++ await expect(page).toHaveURL(/\/verify_email\/[a-zA-Z0-9_.-]*/)+ })+test('Can submit the signup form multiple times if there is a generic email set', async ({ page }) => {let signupRequestBody: string | null = nullconst email = `new_user+generic_error_test_${Math.floor(Math.random() * 10000)}@posthog.com`diff --git a/posthog/api/test/test_signup.py b/posthog/api/test/test_signup.pyindex fb4e73c7e511..322c14a07bc1 100644--- a/posthog/api/test/test_signup.py+++ b/posthog/api/test/test_signup.py@@ -537,6 +537,40 @@ class TestSignupAPI(APIBaseTest):self.assertEqual(Team.objects.count(), team_count)self.assertEqual(Organization.objects.count(), org_count)+ def test_cant_sign_up_with_blank_first_name(self):+ count: int = User.objects.count()+ team_count: int = Team.objects.count()+ org_count: int = Organization.objects.count()++ for first_name in ["", " "]:+ response = self.client.post(+ "/api/signup/",+ {+ "first_name": first_name,+ "email": "[email protected]",+ "password": VALID_TEST_PASSWORD,+ },+ )+ self.assertEqual(+ response.status_code,+ status.HTTP_400_BAD_REQUEST,+ f"first_name {first_name!r} may not be blank",+ )+ self.assertEqual(+ response.json(),+ {+ "type": "validation_error",+ "code": "blank",+ "detail": "This field may not be blank.",+ "attr": "first_name",+ },+ f"first_name {first_name!r} may not be blank",+ )++ self.assertEqual(User.objects.count(), count)+ self.assertEqual(Team.objects.count(), team_count)+ self.assertEqual(Organization.objects.count(), org_count)+def test_cant_sign_up_with_short_password(self):count: int = User.objects.count()team_count: int = Team.objects.count()