1

I have this code:

switch (cpf) {
      case this.aluno.cpf.length == 0:
        this.cpfVazio = true;
      break;

      case this.aluno.cpf.length != 14:
        this.cpfVazio = true;
      break;
      default:
        this.cpfVazio = false;
      break;
    }

this.aluno.cpf is a string. And it is not comparing always going to default. Does anyone know what is wrong?

Here is the HTML code and the class Aluno:

<ion-item>
        <ion-label position="floating">CPF*</ion-label>
        <ion-input type="text" [(ngModel)]="aluno.cpf" [brmasker]="{mask: '000.000.000-00', len:14, type:'num'}" (ionBlur)="validaCpf(aluno.cpf)" (ionChange)="validaCpf(aluno.cpf)" name="cpf" required></ion-input>
      </ion-item>
      <small class="mensagem-erro" *ngIf="cpfVazio" name="cpf">Este campo é obrigatório!</small><br>

export class Aluno {
    inscricao = "";
    dataInscricao = "";
    nome = "";
    dataNascimento = "";
    cpf = "";
    endereco = "";
    cidade = "";
    bairro = "";
    cep = "";
    contatos = "";
    email = "";
    facebook = "";
    igreja = "";
    soube = "";
    proposito = "";
    historico = "";
}
5
  • Do not use a switch but several if. Commented Jan 28, 2020 at 16:42
  • That's not how switch statement works. Commented Jan 28, 2020 at 16:55
  • you are using switch statement incorrectly, Commented Jan 28, 2020 at 16:58
  • What are you actually trying to validate, because maybe minLength and maxLength of 14 would be easier? Commented Jan 28, 2020 at 16:58
  • I want to be sure this.aluno.cpf is equal 14 characters Commented Jan 28, 2020 at 17:52

3 Answers 3

1

For your use case it's better to use an if/else statement. It's way cleaner and easy to reason about.

On the other hand, your switch statement is a bit weird. If you want to use cpf's length then you have to include it in the switch statement like switch (cpf.length) { ... } and then in your case use something like case 0: do something. It will also work with an expression but it's not a pretty solution. Use if/else instead.

Sign up to request clarification or add additional context in comments.

1 Comment

Thx it didn't work with an expression but it worked when I put (cpf.length) and case 0: it worked! dont know why it didnt work the other way!
1

Try this:

if (this.aluno.cpf.length !== 14) {
  this.cpfVazio = true;
} else {
  this.cpfVazio = false;
}

Comments

0

Thx all! It didn't work with an expression but it worked when I put (cpf.length) and case 0: it worked! dont know why it didnt work the other way!

Maybe if I put like this: ´´´ case cpf.length == 0: ´´´ It would work, because I wasnt using the cpf variable inside the switch!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.