When adding a new supplier, you learned in Validating Data In A User Interface about how to ensure that all the required fields are populated before you can click the Add button. If you need to add more validations to your fields, you can do that by using standard Angular Validators or by creating a custom validator.
Standard Validators
Let's say the Supplier code follows the following naming conventions:
- It should have a minimum of 4 characters, and
- It can't have more than 6 characters
If Supplier code field is being used in multiple components, you can create a Supplier Code Field component to override the code field in all of the Supplier Dynamic Components. Add "control" property of type ApexFormControl as an input to this component.
In your template, add a Text Field (Dynamic Components) and set its attribute like this:
Create a method setCodeValidations and set it to call on load with the following code:
this.control.setValidators([Validators.minLength(4), Validators.maxLength(6)]);
minLength and maxLength are standard Angular validators that throw an error when validation fails. The Add button automatically disables when there is a validation error.
Error on entering less than 4 characters:
Error on entering more than 6 characters:
Custom Validators
You can create a custom validator if any of the standard Angular validator is not sufficient. In the example below, we will enforce the Supplier code property to accept only letters. Create a validateCode method with formControl of type FormControl as an input and the following code:
//Check if code has only alphabets
let result;
debug('formControl', formControl);
if (formControl?.value) {
let value = formControl.value;
debug('value', value);
let res = /^[a-zA-Z]+$/.test(value);
debug('res', res);
if (!res) {
result = { invalidCode: { message: 'The code must contain only non-numeric characters.' } };
}
debug('result', result);
return result;
}
As you can see from the line #13 of the above code, you can add any custom message to display on validation error. In this example, we used regex in line #9 to validate the value but you can write any code in standard javascript to validate the value.
Update the setCodeValidations method that you created above in the Standard Validators section, to add this custom validator:
this.control.setValidators([Validators.minLength(4), Validators.maxLength(6), this.validateCode]);
Error on entering numeric characters in the code field: