To handle both string and numerical comparisons effectively in your uniqueCommaValuesValidator, you can enhance the validator to parse the values as numbers (when possible) before checking for uniqueness. This way, values like "20" and "20.00" will be treated as duplicates because they represent the same numerical value.
Here's how you can modify your validator:
import { AbstractControl, ValidationErrors } from '@angular/forms';
export function uniqueCommaValuesValidator(
control: AbstractControl,
): ValidationErrors | null {
if (!control.value) return null;
// Split the input string by commas and trim each value
const values = control.value.split(',').map((v: string) => v.trim());
// Convert values to numbers if possible; otherwise, keep them as strings
const processedValues = values.map(v => {
const num = parseFloat(v);
return isNaN(num) ? v : num;
});
// Use a Set to check for uniqueness
const uniqueValues = new Set(processedValues);
// If there are duplicates, return a validation error
if (processedValues.length !== uniqueValues.size) {
return { duplicateCommaValues: true };
}
return null;
}
Explanation of Changes:
-
Parsing Values as Numbers:
- After splitting and trimming the input string, each value is attempted to be parsed into a number using
parseFloat(v).
- If the parsing results in a valid number (
isNaN(num) returns false), the numerical value is used.
- If the parsing fails (
isNaN(num) returns true), the original string is retained.
const processedValues = values.map(v => {
const num = parseFloat(v);
return isNaN(num) ? v : num;
});
-
Checking for Uniqueness:
- By using a
Set on the processedValues, you ensure that both numerical duplicates (like 20 and 20.00) and string duplicates are identified correctly.
const uniqueValues = new Set(processedValues);
-
Validation Logic:
- If the length of the original
processedValues array doesn't match the size of the Set, it indicates that there are duplicate values.
- In such cases, the validator returns a validation error
{ duplicateCommaValues: true }.
if (processedValues.length !== uniqueValues.size) {
return { duplicateCommaValues: true };
}
Additional Enhancements:
-
Handling Case Sensitivity (Optional):
If your comma-separated values can include strings where case sensitivity matters (e.g., "Apple" vs. "apple"), you might want to normalize the case to ensure accurate duplicate detection.
const processedValues = values.map(v => {
const num = parseFloat(v);
if (!isNaN(num)) return num;
return v.toLowerCase(); // Normalize to lowercase
});
-
Trimming and Removing Empty Values:
Ensure that empty strings resulting from inputs like "10, , 20" are handled appropriately.
const values = control.value
.split(',')
.map((v: string) => v.trim())
.filter(v => v !== '');
Usage Example:
Suppose you have a form control where users input comma-separated values:
<input formControlName="values" />
<div *ngIf="form.controls['values'].hasError('duplicateCommaValues')">
Duplicate values are not allowed.
</div>
This setup ensures that both string and numerical duplicates are correctly identified, providing a more robust validation mechanism for your form.
By implementing these changes, your validator will correctly identify duplicates regardless of whether the values are treated as strings or numbers, ensuring consistent and accurate validation behavior.