1
0
mirror of https://github.com/bitwarden/browser synced 2026-02-20 11:24:07 +00:00
Files
browser/libs/components/src/form-field/bit-validators/trim.validator.ts
Thomas Avery 2f44b9b0dd [SM-628] Add trim validator to SM dialogs (#4993)
* Add trim validator to SM dialogs

* Swap to creating a generic component

* Swap to BitValidators.trimValidator

* Fix storybook

* update validator to auto trim whitespace

* update storybook copy

* fix copy

* update trim validator to run on submit

* add validator to project name in secret dialog; update secret name validation to on submit

---------

Co-authored-by: William Martin <contact@willmartian.com>
2023-05-30 18:52:02 -04:00

28 lines
748 B
TypeScript

import { AbstractControl, FormControl, ValidatorFn } from "@angular/forms";
/**
* Automatically trims FormControl value. Errors if value only contains whitespace.
*
* Should be used with `updateOn: "submit"`
*/
export const trimValidator: ValidatorFn = (control: AbstractControl<string>) => {
if (!(control instanceof FormControl)) {
throw new Error("trimValidator only supports validating FormControls");
}
const value = control.value;
if (value === null || value === undefined || value === "") {
return null;
}
if (!value.trim().length) {
return {
trim: {
message: "input is only whitespace",
},
};
}
if (value !== value.trim()) {
control.setValue(value.trim());
}
return null;
};