Advertisement
Guest User

Untitled

a guest
Mar 15th, 2019
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. ///constraints.ts
  2.  
  3. interface IRule {
  4.     rule: IRuleTypes;
  5.     errorMessage: string;
  6. }
  7. type IRuleTypes = 'required' | ICustomFunction;
  8. type ICustomFunction = ((value: string) => boolean);
  9. type ICustomValue = string;
  10.  
  11. function getConstraintFunction(constraint: IRuleTypes): ICustomFunction {
  12.     switch (constraint) {
  13.         case 'required': {
  14.             return required;
  15.         }
  16.         default: {
  17.             return constraint;
  18.         }
  19.     }
  20. }
  21. function required(value: ICustomValue): boolean {
  22.     switch (typeof value) {
  23.         case 'string':
  24.             return (value as string).length > 0;
  25.     }
  26. }
  27. function checkForErrors(value: string, constraints: IRule[]): string {
  28.     for (const constraint of constraints) {
  29.         if (!checkForError(value, constraint)) {
  30.             return constraint.errorMessage;
  31.         }
  32.     }
  33.  
  34.     return undefined;
  35. }
  36.  
  37. function checkForError(value: string, constraint: IRule): boolean {
  38.     return getConstraintFunction(constraint.rule)(value);
  39. }
  40.  
  41. export default checkForErrors;
  42. export { checkForErrors, IRule };
  43.  
  44.  
  45. /// USAGE
  46. // Imports
  47.  
  48. const constraints: IRule[] = [
  49.     {
  50.         rule: 'required',
  51.         errorMessage: 'Privaloma įvesti esama kilometražą.'
  52.     },
  53.     {
  54.         rule: (value: string) => /^([0-9]+)$/.test(value),
  55.         errorMessage: 'Kilometražas turi būti sveikasis skaičius.'
  56.     },
  57.     {
  58.         rule: (value: string) => /^(0|[1-9][0-9]*)$/.test(value),
  59.         errorMessage: 'Kilometražas negali prasidėti 0.'
  60.     },
  61.     {
  62.         rule: (value: string) => value.length < 7,
  63.         errorMessage: 'Kilometražas negali būti didesnis negu 999 999.'
  64.     }
  65. ]
  66.  
  67. class Something extends React.Component<> {
  68.     //...
  69.  
  70.     private getErrorMessage(): string {
  71.         return this.state.valueChanged ? checkForErrors(this.props.value, constraints) : undefined;
  72.     }
  73.     public hasError(): boolean {
  74.         return this.getErrorMessage() !== undefined;
  75.     }
  76.  
  77.     render() {
  78.         //...
  79.     }
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement