Hone logo
Hone
Problems

Angular Runtime Validation: User Profile Update

This challenge focuses on implementing robust runtime validation for user profile data in an Angular application. You'll create a service that checks incoming user profile updates against predefined rules, ensuring data integrity before it's processed further. This is crucial for maintaining a stable application and preventing invalid data from reaching your backend.

Problem Description

You need to create an Angular service, UserProfileValidatorService, that performs runtime checks on user profile update objects. This service will be responsible for validating various fields within a user profile object according to specific rules.

Requirements:

  • Service Structure: Create a class UserProfileValidatorService within an Angular module (e.g., AppModule or a dedicated CoreModule).
  • Validation Method: Implement a method, validateUpdate(profileUpdate: Partial<UserProfile>), that takes a partial UserProfile object as input and returns a ValidationResult.
  • ValidationResult Interface: Define an interface ValidationResult with the following properties:
    • isValid: boolean: True if all validations pass, false otherwise.
    • errors: { [key: string]: string[] }: An object where keys are field names and values are arrays of error messages for that field. If isValid is true, this object should be empty.
  • Validation Rules: The validateUpdate method should enforce the following rules for the provided profileUpdate object:
    • firstName (Optional): If present, must be at least 2 characters long.
    • lastName (Optional): If present, must be at least 2 characters long.
    • email (Optional): If present, must be a valid email format. A simple regex check for . and @ can suffice for this exercise, e.g., /^\S+@\S+\.\S+$/.test(email).
    • age (Optional): If present, must be a positive integer greater than or equal to 0.
    • phoneNumber (Optional): If present, must contain only digits, spaces, hyphens, and parentheses.
  • Handling Empty Updates: If the profileUpdate object is empty (no properties provided), it should be considered valid.
  • Return Value: The method should return a ValidationResult object indicating the overall validity and any specific field errors.

Expected Behavior:

The UserProfileValidatorService should accurately identify valid and invalid profile updates based on the defined rules. For invalid updates, it should provide clear error messages for each failing field.

Edge Cases to Consider:

  • An empty profileUpdate object.
  • null or undefined values for optional fields.
  • Fields present but with empty strings.
  • Non-string values for fields that expect strings (though TypeScript's type system should help here, consider how your validation handles potential runtime type mismatches if the data source isn't strictly typed).

Examples

Example 1:

Input:
{
  firstName: "John",
  email: "john.doe@example.com",
  age: 30
}

Output:
{
  isValid: true,
  errors: {}
}

Explanation: All provided fields meet their respective validation criteria.

Example 2:

Input:
{
  firstName: "J",
  lastName: "Doe",
  email: "invalid-email",
  age: -5,
  phoneNumber: "123-456-7890 ext. 123"
}

Output:
{
  isValid: false,
  errors: {
    firstName: ["First name must be at least 2 characters long."],
    email: ["Invalid email format."],
    age: ["Age must be a positive integer."]
  }
}

Explanation: firstName is too short, email is not a valid format, and age is negative. phoneNumber is valid. The errors object lists the specific issues.

Example 3:

Input:
{}

Output:
{
  isValid: true,
  errors: {}
}

Explanation: An empty update object is considered valid.

Example 4:

Input:
{
  firstName: "Jane",
  phoneNumber: "123 456 (789)"
}

Output:
{
  isValid: true,
  errors: {}
}

Explanation: All provided fields meet their respective validation criteria. The phoneNumber contains valid characters.

Constraints

  • The UserProfileValidatorService must be implemented in TypeScript.
  • The solution should be self-contained within an Angular service.
  • For the email validation, a simple regex like /^\S+@\S+\.\S+$/ is sufficient. No complex email validation libraries are required.
  • Consider that the input profileUpdate object can have any subset of the UserProfile properties.
  • The service should be efficient enough not to introduce noticeable latency for typical user interactions.

Notes

  • Think about how you can make your validation rules reusable or easily extendable in the future.
  • Consider using Angular's dependency injection to make the service available where needed.
  • The UserProfile interface itself doesn't need to be provided; you should assume it exists and has properties like firstName, lastName, email, age, and phoneNumber. You can define a basic UserProfile interface for your service's type hinting if you wish, but the focus is on the validateUpdate method.
  • Success is defined by the UserProfileValidatorService correctly and consistently validating user profile updates according to the specified rules, returning accurate ValidationResult objects for all scenarios, including edge cases.
Loading editor...
typescript