]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blobdiff - client/src/app/shared/forms/form-reactive.ts
Add contact form checkbox in admin form
[github/Chocobozzz/PeerTube.git] / client / src / app / shared / forms / form-reactive.ts
index 0bb7d25e6f5c606da996ae66195930b9262f14bc..2d0e8359f890cff19dbf1a1683af80cf7af57f89 100644 (file)
@@ -1,11 +1,9 @@
 import { FormGroup } from '@angular/forms'
 import { BuildFormArgument, BuildFormDefaultValues, FormValidatorService } from '@app/shared/forms/form-validators/form-validator.service'
 
-export type FormReactiveErrors = { [ id: string ]: string }
+export type FormReactiveErrors = { [ id: string ]: string | FormReactiveErrors }
 export type FormReactiveValidationMessages = {
-  [ id: string ]: {
-    [ name: string ]: string
-  }
+  [ id: string ]: { [ name: string ]: string } | FormReactiveValidationMessages
 }
 
 export abstract class FormReactive {
@@ -23,29 +21,49 @@ export abstract class FormReactive {
     this.formErrors = formErrors
     this.validationMessages = validationMessages
 
-    this.form.valueChanges.subscribe(() => this.onValueChanged(false))
+    this.form.valueChanges.subscribe(() => this.onValueChanged(this.form, this.formErrors, this.validationMessages, false))
+  }
+
+  protected forceCheck () {
+    return this.onValueChanged(this.form, this.formErrors, this.validationMessages, true)
+  }
+
+  protected check () {
+    return this.onValueChanged(this.form, this.formErrors, this.validationMessages, false)
   }
 
-  protected onValueChanged (forceCheck = false) {
-    for (const field in this.formErrors) {
+  private onValueChanged (
+    form: FormGroup,
+    formErrors: FormReactiveErrors,
+    validationMessages: FormReactiveValidationMessages,
+    forceCheck = false
+  ) {
+    for (const field of Object.keys(formErrors)) {
+      if (formErrors[field] && typeof formErrors[field] === 'object') {
+        this.onValueChanged(
+          form.controls[field] as FormGroup,
+          formErrors[field] as FormReactiveErrors,
+          validationMessages[field] as FormReactiveValidationMessages,
+          forceCheck
+        )
+        continue
+      }
+
       // clear previous error message (if any)
-      this.formErrors[ field ] = ''
-      const control = this.form.get(field)
+      formErrors[ field ] = ''
+      const control = form.get(field)
 
       if (control.dirty) this.formChanged = true
 
       // Don't care if dirty on force check
       const isDirty = control.dirty || forceCheck === true
       if (control && isDirty && !control.valid) {
-        const messages = this.validationMessages[ field ]
+        const messages = validationMessages[ field ]
         for (const key in control.errors) {
-          this.formErrors[ field ] += messages[ key ] + ' '
+          formErrors[ field ] += messages[ key ] + ' '
         }
       }
     }
   }
 
-  protected forceCheck () {
-    return this.onValueChanged(true)
-  }
 }