Skip to content

Validation

digitalkyopo edited this page Oct 20, 2018 · 3 revisions

Validation is used in the Reboot app to validate inputs received from Login, Register, and the Wizard. Angular Formbuilder is used to implement this.

Formbuilder will need to be imported from @angular/forms along with Validators, FormGroup, and FormControl, depending on how you will arrange your validation. For Reboot, creating a FormGroup with individual FormControls was useful. This allows us to individually validate inputs with FormControls and then validate the entire FormGroup before submitting or using the received data.

Here is an example of this used in Registration:

    this.validate = this.formBuilder.group({
      first: ['', Validators.compose([Validators.maxLength(30), Validators.pattern('[a-zA-Z ]*'), 
             Validators.required])],...

The variable "validate" is of type "FormGroup" and an instance of this is created with the FormBuilder.group method. Inside this group are individual FormControls, this one labelled "first" being used to validate the First Name input. The control has predefined properties that are assigned in an array.

  • The first property in the first indice of the array is empty in order to receive the value from the input to be examined.
  • The second indice defines all the validations to be performed. A single validation method can be used here, such as "Validators.required" which simply requires any value to be input. Here, Validators.compose method is used to implement multiple validations which define a max character length, desired regex pattern(Regular Expression), and a required input.
  • The third indice isn't used here, but can be used for asynchronous validation.

Custom validation can also be performed in addition to the predefined validators. Continuing from the previous example Registration FormGroup:

...
  pass: this.formBuilder.group({
    password: ['', Validators.compose([Validators.minLength(6), Validators.maxLength(30), Validators.pattern('[a-zA-Z0-9 
      ]*'), Validators.required])],
    passwordCheck: ['', Validators.required]
  }, {validator: PasswordValidator})
})

Here, "pass" is one of the FormControls of the existing "this.validate" FormGroup. This control is itself another FormGroup which validates the password input and the password match input together.

Clone this wiki locally