@arsedizioni/ars-utils 22.5.28 → 22.5.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -702,118 +702,27 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.3", ngImpor
702
702
  }] });
703
703
 
704
704
  /**
705
- * Signal-forms counterparts of the classic validator directives in this entry point.
706
- *
707
- * The `[formField]` directive only honours `NG_VALIDATORS` providers on ControlValueAccessor
708
- * hosts (custom controls); on native inputs the attribute directives (`password`, `emails`,
709
- * `time`, `equals`) are ignored. Schemas built with `form()` must therefore use these
710
- * functions instead. Error kinds and messages match the directive versions one to one.
711
- */
712
- /**
713
- * Binds a validator requiring the value to be a semicolon-separated list of valid
714
- * email addresses. An empty value is considered valid (pair with `required` if needed).
715
- * Signal-forms counterpart of `EmailsValidatorDirective`.
716
- * @param path - Path of the string field to validate.
717
- */
718
- function emailsValidator(path) {
719
- validate(path, ({ value }) => {
720
- const input = value();
721
- if (!input || input.length === 0)
722
- return undefined;
723
- const parts = input.replaceAll(/\r\n/g, '').split(';');
724
- const isValid = parts.every(part => part.length === 0 || !!SystemUtils.parseEmail(part));
725
- return isValid ? undefined : { kind: 'emails', message: 'Elenco non valido.' };
726
- });
727
- }
728
- /**
729
- * Binds a validator requiring the value to meet the minimum password-strength
730
- * requirements (see `SystemUtils.calculatePasswordStrength`). An empty value is
731
- * INVALID, exactly like the classic directive.
732
- * Signal-forms counterpart of `PasswordValidatorDirective`.
733
- * @param path - Path of the string field to validate.
734
- */
735
- function passwordValidator(path) {
736
- validate(path, ({ value }) => {
737
- const strength = SystemUtils.calculatePasswordStrength(value() ?? '');
738
- return strength.isValid ? undefined : { kind: 'password', message: 'Non valido.' };
739
- });
740
- }
741
- /**
742
- * Binds a validator requiring the value to be a valid `"HH:MM"` time string and,
743
- * when slots are provided, to fall within at least one of the allowed ranges.
744
- * An empty value is considered valid (pair with `required` if needed).
745
- * Signal-forms counterpart of `TimeValidatorDirective`.
746
- * @param path - Path of the string field to validate.
747
- * @param slots - Optional reactive function returning the pipe-separated allowed
748
- * ranges (e.g. `"08:00-12:00|14:00-18:00"`), or `undefined` for none.
749
- */
750
- function timeValidator(path, slots) {
751
- /**
752
- * Parses a `"HH:MM"` time string into a comparable integer (e.g. `"09:30"` -> `930`).
753
- * Returns `-1` when the string is not a valid time.
754
- * @param value - The time string to parse.
755
- * @returns The comparable integer, or `-1` when invalid.
756
- */
757
- const getTime = (value) => {
758
- const p = value.split(':');
759
- if (p.length !== 2)
760
- return -1;
761
- const hh = parseInt(p[0], 10);
762
- if (isNaN(hh) || hh < 0 || hh > 23)
763
- return -1;
764
- const mm = parseInt(p[1], 10);
765
- if (isNaN(mm) || mm < 0 || mm > 59)
766
- return -1;
767
- return hh * 100 + mm;
768
- };
769
- validate(path, ({ value }) => {
770
- const input = value();
771
- if (!input || input.length === 0)
772
- return undefined;
773
- const t = getTime(input);
774
- if (t === -1)
775
- return { kind: 'time', message: 'Non valido.' };
776
- const slotsValue = slots?.();
777
- if (slotsValue) {
778
- const isValid = slotsValue.split('|').some(s => {
779
- const t1 = getTime(s.substring(0, 5));
780
- const t2 = getTime(s.substring(6));
781
- return t1 !== -1 && t2 !== -1 && t1 <= t && t2 >= t;
782
- });
783
- if (!isValid)
784
- return { kind: 'time', message: 'Non valido.' };
785
- }
786
- return undefined;
787
- });
788
- }
789
- /**
790
- * Binds a validator requiring the value to strictly equal the value of another field
791
- * of the same form. Reactive on both fields, so the host field re-validates when the
792
- * other field changes (this replaces the `valueChanges` subscription of the directive).
793
- * Signal-forms counterpart of `EqualsValidatorDirective`.
794
- * @param path - Path of the field to validate.
795
- * @param other - Path of the field whose value must match.
705
+ * Default texts of the rules declared here, in one place so that the validators and the fallback
706
+ * map of `SignalsUtils.getFieldErrorMessage` cannot drift apart: a rule added below without a
707
+ * message here would show "Errore", and one renamed here without touching the validator would
708
+ * leave the map with a kind nobody produces.
796
709
  */
797
- function equalsValidator(path, other) {
798
- validate(path, ctx => ctx.valueOf(other) === ctx.value()
799
- ? undefined
800
- : { kind: 'equals', message: 'Non valido.' });
801
- }
802
- /**
803
- * Binds a validator requiring the value to be either empty or a complete 6-digit
804
- * OTP code. A partial code (e.g. `"12"`) is invalid; emptiness is left to `required`.
805
- * Schema-level counterpart of the `OtpInputComponent` internal validator.
806
- * @param path - Path of the string field to validate.
807
- */
808
- function otpValidator(path) {
809
- validate(path, ({ value }) => {
810
- const input = value() ?? '';
811
- if (input.length === 0)
812
- return undefined;
813
- return /^\d{6}$/.test(input) ? undefined : { kind: 'otp', message: 'Non valido.' };
814
- });
815
- }
816
-
710
+ const ARS_VALIDATOR_MESSAGES = {
711
+ guid: 'Ticket non riconosciuto',
712
+ password: 'Password non sufficientemente robusta',
713
+ notEmpty: 'Non può contenere solo spazi',
714
+ notEqual: 'Deve essere diverso dall\'altro valore',
715
+ sqlDate: 'Data non valida',
716
+ notFuture: 'La data non può essere futura',
717
+ url: 'Indirizzo non valido',
718
+ maxTerms: 'Troppe parole',
719
+ fileSize: 'Dimensione del file non ammessa',
720
+ validIf: 'Non valido',
721
+ emails: 'Elenco non valido',
722
+ time: 'Orario non valido',
723
+ equals: 'I due valori non coincidono',
724
+ otp: 'Codice non valido',
725
+ };
817
726
  /**
818
727
  * Requires the value to be a well-formed GUID / UUID.
819
728
  *
@@ -836,7 +745,7 @@ function guid(path, config) {
836
745
  return null;
837
746
  return SystemUtils.parseUUID(input)
838
747
  ? null
839
- : { kind: 'guid', message: config?.message ?? 'Ticket non riconosciuto' };
748
+ : { kind: 'guid', message: config?.message ?? ARS_VALIDATOR_MESSAGES['guid'] };
840
749
  });
841
750
  }
842
751
  /**
@@ -856,7 +765,7 @@ function password(path, config) {
856
765
  const strength = SystemUtils.calculatePasswordStrength(ctx.value() ?? '');
857
766
  return strength.isValid
858
767
  ? null
859
- : { kind: 'password', message: config?.message ?? 'Password non sufficientemente robusta' };
768
+ : { kind: 'password', message: config?.message ?? ARS_VALIDATOR_MESSAGES['password'] };
860
769
  });
861
770
  }
862
771
  /**
@@ -885,9 +794,343 @@ function notEmpty(path, config) {
885
794
  return null;
886
795
  return input.trim().length > 0
887
796
  ? null
888
- : { kind: 'notEmpty', message: config?.message ?? 'Non può contenere solo spazi' };
797
+ : { kind: 'notEmpty', message: config?.message ?? ARS_VALIDATOR_MESSAGES['notEmpty'] };
798
+ });
799
+ }
800
+ /**
801
+ * Requires the value to differ from the value of another field of the same form.
802
+ *
803
+ * The signal-form counterpart of `NotEqualValidatorDirective`, with its exact rule: two empty
804
+ * values are considered different, so an untouched pair of fields does not start out in error.
805
+ * Reactive on both fields — editing either one re-validates this one, which is what the
806
+ * directive needed a `valueChanges` subscription (and a re-entrancy guard) to achieve.
807
+ *
808
+ * @param path - Path of the field to validate.
809
+ * @param other - Path of the field whose value must differ.
810
+ * @param config - Optional message override and `when` condition.
811
+ * @returns void
812
+ */
813
+ function notEqual(path, other, config) {
814
+ validate(path, ctx => {
815
+ if (config?.when && !config.when(ctx))
816
+ return null;
817
+ const mine = ctx.value();
818
+ const theirs = ctx.valueOf(other);
819
+ const isValid = (!theirs && !mine) || theirs !== mine;
820
+ return isValid ? null : { kind: 'notEqual', message: config?.message ?? ARS_VALIDATOR_MESSAGES['notEqual'] };
821
+ });
822
+ }
823
+ /**
824
+ * Requires the value to be a date the backend can store: parseable, and after 1750.
825
+ *
826
+ * The signal-form counterpart of `SqlDateValidatorDirective`. The year floor is not arbitrary —
827
+ * it is what separates a real date from the 01/01/0001 that a mistyped year produces, which SQL
828
+ * Server rejects with an error nobody can read.
829
+ *
830
+ * @param path - Path of the field to validate.
831
+ * @param config - Optional message override and `when` condition.
832
+ * @returns void
833
+ */
834
+ function sqlDate(path, config) {
835
+ validate(path, ctx => {
836
+ if (config?.when && !config.when(ctx))
837
+ return null;
838
+ const input = ctx.value();
839
+ if (!input || input.length === 0)
840
+ return null;
841
+ const parsed = SystemUtils.parseDate(input);
842
+ const invalid = { kind: 'sqlDate', message: config?.message ?? ARS_VALIDATOR_MESSAGES['sqlDate'] };
843
+ if (!parsed)
844
+ return invalid;
845
+ return endOfDay(parsed).getFullYear() > 1750 ? null : invalid;
846
+ });
847
+ }
848
+ /**
849
+ * Requires the value to be a date that is not in the future.
850
+ *
851
+ * The signal-form counterpart of `NotFutureValidatorDirective`. Today counts as valid: the
852
+ * comparison is made on the end of the day, so a date entered this morning does not become
853
+ * invalid because the clock says 09:00.
854
+ *
855
+ * @param path - Path of the field to validate.
856
+ * @param config - Optional message override and `when` condition.
857
+ * @returns void
858
+ */
859
+ function notFuture(path, config) {
860
+ validate(path, ctx => {
861
+ if (config?.when && !config.when(ctx))
862
+ return null;
863
+ const input = ctx.value();
864
+ if (!input || input.length === 0)
865
+ return null;
866
+ const parsed = SystemUtils.parseDate(input);
867
+ const invalid = { kind: 'notFuture', message: config?.message ?? ARS_VALIDATOR_MESSAGES['notFuture'] };
868
+ if (!parsed)
869
+ return invalid;
870
+ return endOfDay(parsed) <= endOfDay(new Date()) ? null : invalid;
871
+ });
872
+ }
873
+ /**
874
+ * Requires the value to be a well-formed URL. An empty value passes, as everywhere else here.
875
+ *
876
+ * The signal-form counterpart of `UrlValidatorDirective`.
877
+ *
878
+ * @param path - Path of the field to validate.
879
+ * @param config - Optional message override and `when` condition.
880
+ * @returns void
881
+ */
882
+ function url(path, config) {
883
+ validate(path, ctx => {
884
+ if (config?.when && !config.when(ctx))
885
+ return null;
886
+ const input = ctx.value();
887
+ if (!input || input.length === 0)
888
+ return null;
889
+ return SystemUtils.parseUrl(input)
890
+ ? null
891
+ : { kind: 'url', message: config?.message ?? ARS_VALIDATOR_MESSAGES['url'] };
892
+ });
893
+ }
894
+ /**
895
+ * Requires the value to hold no more than `max` whitespace-separated terms.
896
+ *
897
+ * The signal-form counterpart of `MaxTermsValidatorDirective`, used on the search boxes where
898
+ * the backend refuses a query past a certain number of words.
899
+ *
900
+ * @param path - Path of the field to validate.
901
+ * @param max - The maximum number of terms, as a number or a reactive function.
902
+ * @param config - Optional message override and `when` condition.
903
+ * @returns void
904
+ */
905
+ function maxTerms(path, max, config) {
906
+ validate(path, ctx => {
907
+ if (config?.when && !config.when(ctx))
908
+ return null;
909
+ const input = ctx.value();
910
+ if (!input)
911
+ return null;
912
+ const terms = input.match(/\S+/g)?.length ?? 0;
913
+ return terms <= (typeof max === 'function' ? max() : max)
914
+ ? null
915
+ : { kind: 'maxTerms', message: config?.message ?? ARS_VALIDATOR_MESSAGES['maxTerms'] };
916
+ });
917
+ }
918
+ /**
919
+ * Requires the size of the picked file to fall within the allowed range.
920
+ *
921
+ * The signal-form counterpart of `FileSizeValidatorDirective`, and it keeps its shape: the field
922
+ * itself holds the file NAME, while the size arrives from outside — the control that picked the
923
+ * file knows it, the form does not. An empty field passes, so "no file" is `required()`'s call
924
+ * and not a size error.
925
+ *
926
+ * @param path - Path of the field holding the file name.
927
+ * @param sizeMb - The size of the picked file in megabytes, as a reactive function.
928
+ * @param maxSizeMb - The maximum allowed size in megabytes. Defaults to `5`.
929
+ * @param minSizeMb - The minimum required size in megabytes. Defaults to `0`.
930
+ * @param config - Optional message override and `when` condition.
931
+ * @returns void
932
+ */
933
+ function fileSize(path, sizeMb, maxSizeMb = 5, minSizeMb = 0, config) {
934
+ validate(path, ctx => {
935
+ if (config?.when && !config.when(ctx))
936
+ return null;
937
+ if (!ctx.value())
938
+ return null;
939
+ const size = sizeMb() ?? 0;
940
+ const max = typeof maxSizeMb === 'function' ? maxSizeMb() : maxSizeMb;
941
+ const min = typeof minSizeMb === 'function' ? minSizeMb() : minSizeMb;
942
+ return size <= max && size >= min
943
+ ? null
944
+ : { kind: 'fileSize', message: config?.message ?? ARS_VALIDATOR_MESSAGES['fileSize'] };
945
+ });
946
+ }
947
+ /**
948
+ * Requires the value to declare itself valid.
949
+ *
950
+ * The signal-form counterpart of `ValidIfDirective`: when the field holds an object implementing
951
+ * `Validated` the verdict is its own `isValid()`, and when the field is empty the verdict is the
952
+ * `flag`. It is the escape hatch for the composite controls whose validity only they can judge.
953
+ *
954
+ * @param path - Path of the field to validate.
955
+ * @param flag - Verdict used while the field is empty, as a boolean or a reactive function.
956
+ * Defaults to `false`.
957
+ * @param config - Optional message override and `when` condition.
958
+ * @returns void
959
+ */
960
+ function validIf(path, flag = false, config) {
961
+ validate(path, ctx => {
962
+ if (config?.when && !config.when(ctx))
963
+ return null;
964
+ const value = ctx.value();
965
+ let isValid;
966
+ if (!value) {
967
+ isValid = (typeof flag === 'function' ? flag() : flag) === true;
968
+ }
969
+ else {
970
+ try {
971
+ isValid = value.isValid?.() === true;
972
+ }
973
+ catch {
974
+ isValid = false;
975
+ }
976
+ }
977
+ return isValid ? null : { kind: 'validIf', message: config?.message ?? ARS_VALIDATOR_MESSAGES['validIf'] };
978
+ });
979
+ }
980
+ /**
981
+ * Requires the value to be a semicolon-separated list of valid e-mail addresses.
982
+ *
983
+ * The signal-form counterpart of `EmailsValidatorDirective`. An empty value passes, and so does
984
+ * an empty entry between two semicolons: the list is typed by hand and a trailing `;` is not a
985
+ * mistake worth an error.
986
+ *
987
+ * @param path - Path of the field to validate.
988
+ * @param config - Optional message override and `when` condition.
989
+ * @returns void
990
+ */
991
+ function emails(path, config) {
992
+ validate(path, ctx => {
993
+ if (config?.when && !config.when(ctx))
994
+ return null;
995
+ const input = ctx.value();
996
+ if (!input || input.length === 0)
997
+ return null;
998
+ const parts = input.replaceAll(/\r\n/g, '').split(';');
999
+ const isValid = parts.every(part => part.length === 0 || !!SystemUtils.parseEmail(part));
1000
+ return isValid ? null : { kind: 'emails', message: config?.message ?? ARS_VALIDATOR_MESSAGES['emails'] };
1001
+ });
1002
+ }
1003
+ /**
1004
+ * Requires the value to be a `"HH:MM"` time and, when slots are given, to fall inside one of them.
1005
+ *
1006
+ * The signal-form counterpart of `TimeValidatorDirective`. An empty value passes.
1007
+ *
1008
+ * @param path - Path of the field to validate.
1009
+ * @param slots - Optional reactive function returning the pipe-separated allowed ranges
1010
+ * (e.g. `"08:00-12:00|14:00-18:00"`), or `undefined` for no restriction.
1011
+ * @param config - Optional message override and `when` condition.
1012
+ * @returns void
1013
+ */
1014
+ function time(path, slots, config) {
1015
+ /**
1016
+ * Turns `"HH:MM"` into a comparable integer (`"09:30"` -> `930`).
1017
+ * @param value - The time string to parse.
1018
+ * @returns The comparable integer, or `-1` when the string is not a valid time.
1019
+ */
1020
+ const getTime = (value) => {
1021
+ const p = value.split(':');
1022
+ if (p.length !== 2)
1023
+ return -1;
1024
+ const hh = parseInt(p[0], 10);
1025
+ if (isNaN(hh) || hh < 0 || hh > 23)
1026
+ return -1;
1027
+ const mm = parseInt(p[1], 10);
1028
+ if (isNaN(mm) || mm < 0 || mm > 59)
1029
+ return -1;
1030
+ return hh * 100 + mm;
1031
+ };
1032
+ validate(path, ctx => {
1033
+ if (config?.when && !config.when(ctx))
1034
+ return null;
1035
+ const input = ctx.value();
1036
+ if (!input || input.length === 0)
1037
+ return null;
1038
+ const invalid = { kind: 'time', message: config?.message ?? ARS_VALIDATOR_MESSAGES['time'] };
1039
+ const t = getTime(input);
1040
+ if (t === -1)
1041
+ return invalid;
1042
+ const slotsValue = slots?.();
1043
+ if (slotsValue) {
1044
+ const inSlot = slotsValue.split('|').some(s => {
1045
+ const from = getTime(s.substring(0, 5));
1046
+ const to = getTime(s.substring(6));
1047
+ return from !== -1 && to !== -1 && from <= t && to >= t;
1048
+ });
1049
+ if (!inSlot)
1050
+ return invalid;
1051
+ }
1052
+ return null;
1053
+ });
1054
+ }
1055
+ /**
1056
+ * Requires the value to equal the value of another field of the same form.
1057
+ *
1058
+ * The signal-form counterpart of `EqualsValidatorDirective`. Reactive on both fields, which is
1059
+ * what the directive needed a `valueChanges` subscription to obtain: retyping the first password
1060
+ * re-validates the confirmation without anyone wiring the two together.
1061
+ *
1062
+ * @param path - Path of the field to validate.
1063
+ * @param other - Path of the field whose value must match.
1064
+ * @param config - Optional message override and `when` condition.
1065
+ * @returns void
1066
+ */
1067
+ function equals(path, other, config) {
1068
+ validate(path, ctx => {
1069
+ if (config?.when && !config.when(ctx))
1070
+ return null;
1071
+ return ctx.valueOf(other) === ctx.value()
1072
+ ? null
1073
+ : { kind: 'equals', message: config?.message ?? ARS_VALIDATOR_MESSAGES['equals'] };
1074
+ });
1075
+ }
1076
+ /**
1077
+ * Requires the value to be either empty or a complete six-digit one-time code.
1078
+ *
1079
+ * The schema-level counterpart of the validator inside `OtpInputComponent`: a partial code is an
1080
+ * error, an empty one is `required()`'s business.
1081
+ *
1082
+ * @param path - Path of the field to validate.
1083
+ * @param config - Optional message override and `when` condition.
1084
+ * @returns void
1085
+ */
1086
+ function otp(path, config) {
1087
+ validate(path, ctx => {
1088
+ if (config?.when && !config.when(ctx))
1089
+ return null;
1090
+ const input = ctx.value() ?? '';
1091
+ if (input.length === 0)
1092
+ return null;
1093
+ return /^\d{6}$/.test(input)
1094
+ ? null
1095
+ : { kind: 'otp', message: config?.message ?? ARS_VALIDATOR_MESSAGES['otp'] };
889
1096
  });
890
1097
  }
1098
+ /** Helpers around signal forms that are not validators themselves. */
1099
+ class SignalsUtils {
1100
+ /**
1101
+ * Builds the error text for a signal-forms field.
1102
+ *
1103
+ * Deliberately dumb: the wording lives in the schema, next to the rule that produces it
1104
+ * (`required(p.x, { message: ... })`), so a field says what is wrong with it in one place
1105
+ * instead of here in a switch that has to guess from the error kind. The map below is only
1106
+ * the safety net for the rules declared without a message — the Angular built-ins, plus
1107
+ * {@link ARS_VALIDATOR_MESSAGES} for the ones declared in this file.
1108
+ * @param errors - The errors currently on the field, from `f.x().errors()`.
1109
+ * @param message - Optional override applied to every error of the field.
1110
+ * @returns The first relevant error text, or `undefined` when the field has no errors.
1111
+ */
1112
+ static getFieldErrorMessage(errors, message) {
1113
+ if (!errors || errors.length === 0)
1114
+ return undefined;
1115
+ const fallback = {
1116
+ // Angular built-ins declared without a message of their own.
1117
+ required: 'Obbligatorio',
1118
+ min: 'Valore troppo basso',
1119
+ max: 'Valore troppo alto',
1120
+ minLength: 'Testo troppo corto',
1121
+ maxLength: 'Testo troppo lungo',
1122
+ pattern: 'Formato non valido',
1123
+ email: 'Indirizzo email non valido',
1124
+ minDate: 'Data troppo indietro',
1125
+ maxDate: 'Data troppo avanti',
1126
+ parse: 'Valore non valido',
1127
+ // The rules of this file, from the single table above: adding a validator there is enough,
1128
+ // and this map can never fall behind it.
1129
+ ...ARS_VALIDATOR_MESSAGES,
1130
+ };
1131
+ return message ?? errors[0].message ?? fallback[errors[0].kind] ?? 'Errore';
1132
+ }
1133
+ }
891
1134
 
892
1135
  /*
893
1136
  * Public API Surface of @arsedizioni/ars-utils/core.validators
@@ -902,5 +1145,5 @@ function notEmpty(path, config) {
902
1145
  * Generated bundle index. Do not edit.
903
1146
  */
904
1147
 
905
- export { EmailsValidatorDirective, EqualsValidatorDirective, FileSizeValidatorDirective, GuidValidatorDirective, MaxTermsValidatorDirective, NotEmptyValidatorDirective, NotEqualValidatorDirective, NotFutureValidatorDirective, PasswordValidatorDirective, SqlDateValidatorDirective, TimeValidatorDirective, UrlValidatorDirective, ValidIfDirective, ValidatorDirective, emailsValidator, equalsValidator, guid, notEmpty, otpValidator, password, passwordValidator, timeValidator };
1148
+ export { ARS_VALIDATOR_MESSAGES, EmailsValidatorDirective, EqualsValidatorDirective, FileSizeValidatorDirective, GuidValidatorDirective, MaxTermsValidatorDirective, NotEmptyValidatorDirective, NotEqualValidatorDirective, NotFutureValidatorDirective, PasswordValidatorDirective, SignalsUtils, SqlDateValidatorDirective, TimeValidatorDirective, UrlValidatorDirective, ValidIfDirective, ValidatorDirective, emails, equals, fileSize, guid, maxTerms, notEmpty, notEqual, notFuture, otp, password, sqlDate, time, url, validIf };
906
1149
  //# sourceMappingURL=arsedizioni-ars-utils-core.validators.mjs.map