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
UserProfileValidatorServicewithin an Angular module (e.g.,AppModuleor a dedicatedCoreModule). - Validation Method: Implement a method,
validateUpdate(profileUpdate: Partial<UserProfile>), that takes a partialUserProfileobject as input and returns aValidationResult. ValidationResultInterface: Define an interfaceValidationResultwith 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. IfisValidis true, this object should be empty.
- Validation Rules: The
validateUpdatemethod should enforce the following rules for the providedprofileUpdateobject: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
profileUpdateobject is empty (no properties provided), it should be considered valid. - Return Value: The method should return a
ValidationResultobject 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
profileUpdateobject. nullorundefinedvalues 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
UserProfileValidatorServicemust 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
profileUpdateobject can have any subset of theUserProfileproperties. - 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
UserProfileinterface itself doesn't need to be provided; you should assume it exists and has properties likefirstName,lastName,email,age, andphoneNumber. You can define a basicUserProfileinterface for your service's type hinting if you wish, but the focus is on thevalidateUpdatemethod. - Success is defined by the
UserProfileValidatorServicecorrectly and consistently validating user profile updates according to the specified rules, returning accurateValidationResultobjects for all scenarios, including edge cases.