If you're familiar with regex patterns, utilizing Validators.pattern
is one way to validate input. However, creating a custom validator can be more manageable and easier to understand compared to using a complex regex pattern. With a custom validator, you have the ability to provide tailored error messages for validation issues. Essentially, a custom validator is a function that either returns an object if the validation fails or null if it succeeds.
Implementing a custom validator for reactive forms:
import { AbstractControl, ValidationErrors } from "@angular/forms"
export const inputTextValidator = function inputTextValidator(control: AbstractControl): ValidationErrors | null {
let getErrorObject = function (message): ValidationErrors {
return {
inputText: true,
message // customized error message related to the validation rule
}
}
let value: string = control.value || '';
// Checking if the value's length falls within a specific range, e.g., 7-25 characters
if (value.length < 7 && value.length < 25) {
return getErrorObject(`The text length must be between 7-25, current length: ${value.length}`);
}
// Validating for invalid characters such as #$%^%$^/-+
let validCharacters = /^[a-zA-Z0-9\*]+$/g
if (validCharacters.test(value) === false) {
return getErrorObject(`The text contains invalid characters, current value: ${value.length}`);
}
let asterisk = /^\w+\*?$/g
if (asterisk.test(value) === false) {
return getErrorObject(`Only one asterisk is allowed at the end of the string, current value: ${value.length}`);
}
// Verifying the position of the asterisk at 8th-13th index
let indexOfAsterisk: number = value.indexOf('*'); // zero-based index
if (indexOfAsterisk >= 0 && (indexOfAsterisk < 8 || indexOfAsterisk > 12)) {
return getErrorObject(`Asterisk must be positioned at 8-13, current * position: ${indexOfAsterisk}`);
}
return null;
}
The example you provided suggests starting the asterisk from the 5th position, conflicting with the minimum value length criteria. Hence, I ensured that the minimum length requirement is at least 8 characters in order to address this discrepancy.
Here is a StackBlitz example for reference