Skip to content

Conversation

@KaranUnique
Copy link
Contributor

@KaranUnique KaranUnique commented Dec 15, 2025

Fixes Issue #2695

Changes proposed

Fixed signup API integration to ensure successful user registration

  • Matched frontend request payload with backend validation schema
  • Added proper async/await and response status handling
  • Implemented clear and meaningful error messages instead of a generic “Signup failed” popup
  • Redirected users to the login/dashboard page after successful signup
  • Improved frontend error handling for validation, duplicate email, and server errors

Note to reviewers

  • Please verify signup flow with both valid and invalid inputs
  • Backend must be running for full end-to-end testing

Summary by CodeRabbit

Release Notes

  • New Features
    • Added real-time form validation with instant error feedback for all signup fields
    • Implemented password strength indicator during signup process
    • Enhanced error messaging with specific feedback for validation failures
    • Improved form submission with pre-validation checks before server requests
    • Maintained social login functionality seamlessly with new validation system

✏️ Tip: You can customize this high-level summary in your review settings.

@vercel
Copy link

vercel bot commented Dec 15, 2025

@KaranUnique is attempting to deploy a commit to the Vivek Prajapati's projects Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 15, 2025

Walkthrough

This PR enhances the UserAuth component with comprehensive inline form validation, adding real-time validation for username, email, phone, and password fields. It introduces pre-submission frontend validations, improves error handling with granular server response differentiation, and updates the form UI to display validation states with dynamic borders and error messages while maintaining existing social login functionality.

Changes

Cohort / File(s) Summary
Form Validation & Signup Enhancement
src/User/pages/UserAuth/UserAuth.jsx
Introduced inline form validation state (usernameError, emailError, phoneError, passwordError, confirmPasswordError) with corresponding validators. Added real-time validation hooks on onChange/onBlur events for immediate feedback. Enhanced signup flow with pre-submission frontend validations (password match, phone format, password length, username length) and API URL resolution using environment variable. Implemented granular error handling for server responses (400, 409, 500) with detailed Swal alerts. Updated signup success handling to clear fields, reset state, show success alert, and return to login. Modified form UI to reflect validation states with per-field error messaging, dynamic border colors, and password strength visualization. Preserved social login logic.

Sequence Diagram

sequenceDiagram
    participant User
    participant Form as Form Component
    participant Validation as Validation Logic
    participant API as API Server
    participant Alert as Swal Alert

    User->>Form: Enter credentials
    Form->>Validation: onChange/onBlur triggered
    activate Validation
    Validation->>Form: Update error state<br/>(username, email, phone, password)
    Form->>User: Display inline errors<br/>(dynamic border colors)
    deactivate Validation

    User->>Form: Click Submit
    Form->>Validation: Pre-submission checks<br/>(password match, phone format,<br/>length requirements)
    alt Validation fails
        Validation-->>Form: Return error state
        Form-->>User: Display error highlights
    else Validation passes
        Form->>API: POST signup request<br/>(env-based URL)
        activate API
        alt Success (2xx)
            API->>Form: Return user data
            Form->>Alert: Show success alert
            Alert->>User: Confirm signup success
            Form->>Form: Clear fields, reset state
            Form->>User: Flip to login view
        else Error (400/409/500)
            API->>Form: Return error response
            Form->>Validation: Differentiate error type
            Validation->>Alert: Granular error message
            Alert->>User: Display error title & details
        else Network Error
            Form->>Alert: Network issue alert
            Alert->>User: Display connection error
        end
        deactivate API
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Areas requiring extra attention:

  • Validation logic patterns and completeness across all five form fields (username, email, phone, password, confirmPassword)
  • Error state differentiation and granular Swal alert handling for various HTTP status codes (400, 409, 500) and network failures
  • Pre-submission validation order and interaction with API submission logic
  • Password strength state reset and form field clearing behavior in success scenario
  • Environment variable fallback configuration and API URL construction

Possibly related PRs

Suggested labels

level3, gssoc

Suggested reviewers

  • codervivek5

Poem

🐰 A form that validates with grace,
Each field now has its rightful place,
Real-time checks and error signs,
Borders glow in smart designs!
Signup flow now stands so tall,
With validations catching all! 🎉

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title directly addresses the main changes: fixing signup failures and improving error handling with user feedback, which aligns with the core objectives.
Description check ✅ Passed The description includes the required sections (Fixes Issue, Changes proposed, Note to reviewers) with sufficient detail about the improvements made to signup flow and error handling.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/User/pages/UserAuth/UserAuth.jsx (1)

327-330: Use environment variable for Google OAuth URL to match backend configuration.

The Google login handler uses a hardcoded http://localhost:3000 while login and signup correctly use import.meta.env.VITE_API_URL || "http://localhost:5000". The backend runs on port 5000 (as configured in backend/.env.example and the Google callback URL), so the Google OAuth flow will fail in production and create inconsistency in development.

    } else if (provider === "google") {
-     const apiUrl =
-       "http://localhost:3000";
+     const apiUrl = import.meta.env.VITE_API_URL || "http://localhost:5000";
      // Google ke liye backend par redirect karein
      window.location.href = `${apiUrl}/auth/google`;
    }
🧹 Nitpick comments (2)
src/User/pages/UserAuth/UserAuth.jsx (2)

216-221: Remove debug console.log statements before production.

These logging statements expose request details (including email) in the browser console and should be removed or wrapped in a development-only check.

-      console.log("🚀 Attempting signup with:", {
-        username,
-        email: signupEmail,
-        phone,
-        apiUrl: `${apiUrl}/auth/signup`
-      });

Also remove related logs at lines 230, 253, 264, 284, and 289.


199-210: Consider adding email validation to pre-submission checks.

Other fields (username, phone, password) have pre-submission validation, but email relies solely on inline validation. For consistency and defense-in-depth, consider adding email validation here.

    // Validate username length
    if (username.length < 3) {
      await Swal.fire({
        title: "Invalid Username",
        text: "Username must be at least 3 characters long.",
        icon: "error",
        confirmButtonText: "OK",
      });
      return;
    }

+   // Validate email format
+   const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
+   if (!emailRegex.test(signupEmail)) {
+     await Swal.fire({
+       title: "Invalid Email",
+       text: "Please enter a valid email address.",
+       icon: "error",
+       confirmButtonText: "OK",
+     });
+     return;
+   }
+
    setLoading(true);
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b9b61e2 and 944b294.

📒 Files selected for processing (1)
  • src/User/pages/UserAuth/UserAuth.jsx (5 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
src/User/pages/UserAuth/UserAuth.jsx (1)
backend/controllers/authController.js (1)
  • req (68-121)
🔇 Additional comments (6)
src/User/pages/UserAuth/UserAuth.jsx (6)

43-48: LGTM!

Clean and properly structured state declarations for inline validation errors.


52-97: LGTM!

Validation rules correctly match backend requirements (username ≥3 chars, password ≥8 chars, 10-digit phone). The closure capture of signupPassword in validateConfirmPassword works correctly in the current usage context.


680-697: LGTM!

The disabled state logic correctly prevents submission when validation errors exist, and the visual feedback with opacity and cursor changes provides clear UX. The loading state enhancement with "Creating Account..." text is a nice touch.


559-584: LGTM!

Good input sanitization that restricts to digits only, with appropriate maxLength attribute. The validation timing (on 10 digits or blur) provides good real-time feedback.


597-604: Good UX consideration.

Re-validating confirmPassword when the password field changes (line 603) ensures the match state stays current if the user modifies their password after filling the confirmation field.


165-208: LGTM!

Pre-submission validation correctly guards against invalid data before making the API call. The sequential validation approach (showing one error at a time) is acceptable UX.

Comment on lines +266 to +281
switch (status) {
case 400:
errorTitle = "Invalid Input";
errorMessage = data.message || "Please check your input and try again.";
break;
case 409:
errorTitle = "Account Already Exists";
errorMessage = data.message || "An account with this email or username already exists.";
break;
case 500:
errorTitle = "Server Error";
errorMessage = "Our server encountered an error. Please try again later.";
break;
default:
errorMessage = data.message || "An unexpected error occurred.";
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Status code mismatch with backend - 409 handler will never trigger.

The backend (from authController.js) returns 400 for duplicate email/username errors, not 409. This means users with duplicate accounts will see the generic "Invalid Input" message instead of "Account Already Exists".

Either update the backend to return 409 for conflicts, or handle duplicates based on the error message:

          case 400:
-           errorTitle = "Invalid Input";
-           errorMessage = data.message || "Please check your input and try again.";
+           // Check if it's a duplicate account error
+           if (data.message?.includes("already exists")) {
+             errorTitle = "Account Already Exists";
+             errorMessage = data.message;
+           } else {
+             errorTitle = "Invalid Input";
+             errorMessage = data.message || "Please check your input and try again.";
+           }
            break;
-         case 409:
-           errorTitle = "Account Already Exists";
-           errorMessage = data.message || "An account with this email or username already exists.";
-           break;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
switch (status) {
case 400:
errorTitle = "Invalid Input";
errorMessage = data.message || "Please check your input and try again.";
break;
case 409:
errorTitle = "Account Already Exists";
errorMessage = data.message || "An account with this email or username already exists.";
break;
case 500:
errorTitle = "Server Error";
errorMessage = "Our server encountered an error. Please try again later.";
break;
default:
errorMessage = data.message || "An unexpected error occurred.";
}
switch (status) {
case 400:
// Check if it's a duplicate account error
if (data.message?.includes("already exists")) {
errorTitle = "Account Already Exists";
errorMessage = data.message;
} else {
errorTitle = "Invalid Input";
errorMessage = data.message || "Please check your input and try again.";
}
break;
case 500:
errorTitle = "Server Error";
errorMessage = "Our server encountered an error. Please try again later.";
break;
default:
errorMessage = data.message || "An unexpected error occurred.";
}

@vercel
Copy link

vercel bot commented Dec 16, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Review Updated (UTC)
vigybag Ready Ready Preview, Comment Dec 16, 2025 8:13am

@codervivek5 codervivek5 merged commit 80dddf2 into codervivek5:main Dec 16, 2025
3 checks passed
@github-actions
Copy link

Congratulations, Your pull request has been successfully merged 🥳🎉 Thank you for your valuable contribution to the project 🚀 Keep contributing!! ✨

📢 Don’t forget to share your VigyBag PR on LinkedIn and tag @VigyBag and me — we’d love to celebrate your achievement with you! 🔗💡

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants