Formgroup Angular

Asked

Viewed 2,028 times

1

Hi, I’m new to angular and would like to know how I use more than one sternal validation with Formgroup. Currently my code is as follows...

constructor(fb: FormBuilder, public router: Router){
        //Grupo de formulario - Validações
        this.myForm = fb.group({
            nome: ['', Validators.required ],
            email: ['', Validators.compose([Validators.required, Validators.pattern(this.emailPattern)])],
            cpf: ['', Validators.required ],
            telefone: ['', Validators.required],
            cep: ['', Validators.required]
        }, { validator: VwPagePersonal.validaNome });
    }

    //Validações customizadas
    static validaNome(group: AbstractControl): {[Key: string]: boolean} {
        const nome = group.get('nome');

        if(!nome){
            return undefined;
        }

        var regexp = /\b[^\d\s]+\b/g;
        var count = 0;
        while (regexp.exec(nome.value))++count;

        if (count === 1) {
            return { nomeInvalid:true }    
        }

        return undefined;    
    }

    static validaCpf(group: AbstractControl): {[Key: string]: boolean} {
        const cpf = group.get('cpf').value;

        if(cpf === 1){
            return { nomeInvalid:true }    
        }

        return undefined;
    }   

I have two external functions, one is: 'Validanome' and the other 'Validacpf'!! However I am only able to use one of the validations in this syntax ", { validator: VwPagePersonal.validaNome });", that is in formGroup!!

I would like to know how I can use both functions together...

  • You want to have your functions available in Validator?

  • Yes. Basically I would like to create 2 new types of validations, like a customization. And it uses them as if they were native Formgroup validations. In this current syntax, the 'validaName' works, now I need the syntax that makes both methods work...

1 answer

1


To create your own custom validation to be used in all your codes of project I recommend creating a file with these functions that extend Formcontrol. Here is an example I took from the site I refer to here.

Declaration in a file

import { FormControl } from '@angular/forms';

function validateEmail(c: FormControl) {
  let EMAIL_REGEXP = ...

  return EMAIL_REGEXP.test(c.value) ? null : {
    validateEmail: {
      valid: false
    }
  };
}

Calling for:

this.form = new FormGroup({
    ...
    email: new FormControl('', [
      Validators.required,
      validateEmail
    ])
  });

If you only need it for a simple call to this file just pass its functions to formControl , as in the example below that is defined here. on the Angular website:

this.heroForm = new FormGroup({
    'name': new FormControl(this.hero.name, [
      Validators.required,
      Validators.minLength(4),
      forbiddenNameValidator(/bob/i) // <-- Here's how you pass in the custom validator.
    ]),
    'alterEgo': new FormControl(this.hero.alterEgo),
    'power': new FormControl(this.hero.power, Validators.required)
  });

With the function definition below:

/** A hero's name can't match the given regular expression */
export function forbiddenNameValidator(nameRe: RegExp): ValidatorFn {
  return (control: AbstractControl): {[key: string]: any} => {
    const forbidden = nameRe.test(control.value);
    return forbidden ? {'forbiddenName': {value: control.value}} : null;
  };
}

Note that I put here only examples to help you create its own functions.

For your current example try to pass an array of validators: Thus:

this.myForm = fb.group({
            nome: new FormCotrol('',[ Validators.required,validaNome]),
} 
  • Dude, perfect, worked great! Thank you so much...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.