javascript - Angular form keep returning false (Angular 2) - Stack Overflow

I have a form in Angular 2 which I'm validating by the model-driven way. I wanna know how do I cha

I have a form in Angular 2 which I'm validating by the model-driven way. I wanna know how do I change the status from false to true, because I have the rules of validation and even if the user fills everything right, it keeps returning me invalid (false). Here's the HTML code.

<div class="wrap-page">
  <form [formGroup]="myForm" novalidate class="form-contato" (ngSubmit)="enviarMensagem(myForm.value, myForm.valid)">
    <div class=row>
      <div class="col s12">
        <h4> Contato </h4>
      </div>
      <div class="col s12 m12 l6">
        <label> Nome: </label>
        <input type="text" name="nome" formControlName="nome" class="forms-econ" required placeholder="ex: José Silva">
        <div class="div-validar">
          <span [hidden]="myForm.controls.nome.valid || (myForm.controls.nome.pristine && !submitted)">
            Nome Inválido (mínimo 3 caracteres).
          </span>
        </div>
      </div>
      <div class="col s12 l6">
        <label> E-mail: </label>
        <input type="email" class="forms-econ" formControlName="email" required name="email" pattern="^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$"
          placeholder="[email protected]">
        <div class="div-validar">
          <span [hidden]="myForm.controls.email.valid || (myForm.controls.email.pristine && !submitted)">
            E-Mail inválido
          </span>
        </div>
      </div>


      <div class="col s12 l6">
        <label>Telefone: </label>
        <input type="tel" class="forms-econ" name="telefone" formControlName="telefone" pattern="[0-9]" placeholder="(xx)9 9999-99999">
      </div>
      <div class="col s12 l6">
        <label> Motivo do Contato: </label>
        <select name="assunto" formControlName="assunto" class="forms-econ">
          <option value="motivo_01">Motivo 01</option>
          <option value="motivo_02">Motivo 02</option>
          <option value="motivo_03">Motivo 03</option>
          <option value="motivo_03">Motivo 04</option>
        </select>

      </div>
      <div class="col s12">
        <label> Mensagem: </label>
        <textarea name="mensagem" formControlName="mensagem" placeholder="Mensagem..." rows="15"> 
        </textarea>
        <div class="div-validar">
          <span [hidden]="myForm.controls.mensagem.valid || (myForm.controls.mensagem.pristine && !submitted)">
            O campo mensagem é obrigatório
          </span>
        </div>
      </div>
       <div class="col s12">
        <label> ID: </label>
        <textarea name="id" formControlName="id" placeholder="Mensagem..." rows="15"> 
        </textarea>
      </div>
      <h1> {{myForm.valid | json}} </h1> // <-- Here is where I'm printing the status of the form (always return false)
      <div class="col s12 right-align">
        <input type="submit" value="Enviar" class="btn-form">
      </div>

    </div>
  </form>
</div>

And here is the ponent.

import { Component, Input } from '@angular/core';
import {FormGroup, FormControl, FormBuilder, Validators} from '@angular/forms';
import {formContato} from './contato.interface';
import {ContatoService} from './contato.service';

@Component({
  moduleId: module.id,
  selector: 'contato',
  templateUrl: `contatoponent.html`,
  providers: [ContatoService]
})
export class ContatoComponent  { 

  public contato:formContato;
  public myForm: FormGroup;
  public submitted: boolean; 
  public events: any[] = []; 

  constructor(private _fb: FormBuilder, private mensagemContato:ContatoService) { } 

    ngOnInit() {  
      this.myForm = this._fb.group({
        nome: ['', [<any>Validators.required, <any>Validators.minLength(3)]],
        email: ['', <any>Validators.required],
        telefone: ['', <any>Validators.required],
        assunto: ['', <any>Validators.required],
        mensagem: ['', <any>Validators.required],
        id: ['']
      })      
    }


    enviarMensagem(model: formContato, isValid: boolean) {
        this.submitted = true;      
        console.log(model, isValid); // -< another way to print the status of the form (always false)
    }
}

Thanks in advance :)

I have a form in Angular 2 which I'm validating by the model-driven way. I wanna know how do I change the status from false to true, because I have the rules of validation and even if the user fills everything right, it keeps returning me invalid (false). Here's the HTML code.

<div class="wrap-page">
  <form [formGroup]="myForm" novalidate class="form-contato" (ngSubmit)="enviarMensagem(myForm.value, myForm.valid)">
    <div class=row>
      <div class="col s12">
        <h4> Contato </h4>
      </div>
      <div class="col s12 m12 l6">
        <label> Nome: </label>
        <input type="text" name="nome" formControlName="nome" class="forms-econ" required placeholder="ex: José Silva">
        <div class="div-validar">
          <span [hidden]="myForm.controls.nome.valid || (myForm.controls.nome.pristine && !submitted)">
            Nome Inválido (mínimo 3 caracteres).
          </span>
        </div>
      </div>
      <div class="col s12 l6">
        <label> E-mail: </label>
        <input type="email" class="forms-econ" formControlName="email" required name="email" pattern="^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$"
          placeholder="[email protected]">
        <div class="div-validar">
          <span [hidden]="myForm.controls.email.valid || (myForm.controls.email.pristine && !submitted)">
            E-Mail inválido
          </span>
        </div>
      </div>


      <div class="col s12 l6">
        <label>Telefone: </label>
        <input type="tel" class="forms-econ" name="telefone" formControlName="telefone" pattern="[0-9]" placeholder="(xx)9 9999-99999">
      </div>
      <div class="col s12 l6">
        <label> Motivo do Contato: </label>
        <select name="assunto" formControlName="assunto" class="forms-econ">
          <option value="motivo_01">Motivo 01</option>
          <option value="motivo_02">Motivo 02</option>
          <option value="motivo_03">Motivo 03</option>
          <option value="motivo_03">Motivo 04</option>
        </select>

      </div>
      <div class="col s12">
        <label> Mensagem: </label>
        <textarea name="mensagem" formControlName="mensagem" placeholder="Mensagem..." rows="15"> 
        </textarea>
        <div class="div-validar">
          <span [hidden]="myForm.controls.mensagem.valid || (myForm.controls.mensagem.pristine && !submitted)">
            O campo mensagem é obrigatório
          </span>
        </div>
      </div>
       <div class="col s12">
        <label> ID: </label>
        <textarea name="id" formControlName="id" placeholder="Mensagem..." rows="15"> 
        </textarea>
      </div>
      <h1> {{myForm.valid | json}} </h1> // <-- Here is where I'm printing the status of the form (always return false)
      <div class="col s12 right-align">
        <input type="submit" value="Enviar" class="btn-form">
      </div>

    </div>
  </form>
</div>

And here is the ponent.

import { Component, Input } from '@angular/core';
import {FormGroup, FormControl, FormBuilder, Validators} from '@angular/forms';
import {formContato} from './contato.interface';
import {ContatoService} from './contato.service';

@Component({
  moduleId: module.id,
  selector: 'contato',
  templateUrl: `contato.ponent.html`,
  providers: [ContatoService]
})
export class ContatoComponent  { 

  public contato:formContato;
  public myForm: FormGroup;
  public submitted: boolean; 
  public events: any[] = []; 

  constructor(private _fb: FormBuilder, private mensagemContato:ContatoService) { } 

    ngOnInit() {  
      this.myForm = this._fb.group({
        nome: ['', [<any>Validators.required, <any>Validators.minLength(3)]],
        email: ['', <any>Validators.required],
        telefone: ['', <any>Validators.required],
        assunto: ['', <any>Validators.required],
        mensagem: ['', <any>Validators.required],
        id: ['']
      })      
    }


    enviarMensagem(model: formContato, isValid: boolean) {
        this.submitted = true;      
        console.log(model, isValid); // -< another way to print the status of the form (always false)
    }
}

Thanks in advance :)

Share Improve this question asked Feb 22, 2017 at 20:05 Renê Silva LimaRenê Silva Lima 2,8152 gold badges14 silver badges20 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

Your problem is with the e-mail and phone validation. They always validate as false.

Since you are using a reactive form, I would suggest you move your pattern checks to your build of the form, e.g:

email: ['', [<any>Validators.required, Validators.pattern(....)]],

Then I would assume that you want to inform right from the beginning that fields are required. This can be done in quite a few ways, here I show two possible solutions:

<span *ngIf="myForm.get('nome').hasError('required')">
   Name required!
</span><br>

or:

<span *ngIf="!myForm.controls.nome.pristine">
   Name required!
</span><br>

and as mentioned in other answer, you need not to pass the myForm.valid in the submit.

I made a Plunker for you, where I set another e-mail validation:

EMAIL_REGEXP = '^[a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,15})$';

and just a random phone number validation, since I wasn't sure exactly what kind of number validation you need. This one checks that the phone number only contains numbers.

If you want you could also disable the submit button if the form is not valid:

<input [disabled]="!myForm.valid" type="submit" value="Enviar" class="btn-form">

but that is of course up to you! :)

Hope this helps!

In Angular 2 , its not required to pass the valid entity on (ngSubmit) , just pass the required form name give to the form group directive .

(ngSubmit)="enviarMensagem(myForm)"


enviarMensagem({model, valid }: {model: Object, valid: boolean}) {
    this.submitted = true;      
    console.log(model, valid); 
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744247826a4565023.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信