Angular (8) form validation message

Asked

Viewed 699 times

0

I’m working on an Input that needs to have a message :

Type at least 10 characters

that message should change with each character that is typed

So, when you type:

Alex

the message should be:

Type at least 6 more characters

my problem is how to get the string size:

<input
type="text"
formControlName="nome" 
class="form-control"
[ngClass]="{'is-invalid': submitted && nome.invalid && (nome.dirty || nome.touched), 'is-valid': (nome.valid && nome.touched ) }">

.

<div class="text-muted" *ngIf="nome?.value.length < 10 ">
digite pelo menos mais {{10 - nome?.value.length }} caracteres </div>

But when starting the "name" this Undefined, and it breaks the application,

any suggestions?

2 answers

2

A simple fit would be, create a get for your form

get formControl() { return this.form.controls; }

in html:

formControl.nome.length < 10

but the correct thing to do is to create a Validator, create a ts file or a function

function minCaracterValue(control: AbstractControl): { [key: string]: boolean } | null {
   if (control.value && (isNaN(control.value) || control.value < 10) {
      return { 'minCaracter': true };
   }
   return null;
}

or it could be a method in the class as well. The form would look like this

  this.form= new FormGroup({
       nome: new FormControl(null, [minCaracterValue])
    });

in your html template would look like this

<p *ngIf="formControl.nome.errors.minCaracter">digite pelo menos mais {{10 - formControl.nome.value }} caracteres</p>

0

Error can be corrected by double use of Elvis Operator

name? .value.length

does not work because value is also null,

should be:

name.value?. length

or

name?. value?. length

  • 1

    And how did you add the word "more"? When there is something typed, according to the question, the phrase needs to be "at least plus X characters". And if 12 characters are typed, "at least plus -2 characters"?

  • I set the question, , now the word 'more' exists from the beginning. .

  • 2

    Um, instead of adapting the solution you adapt the problem? haha xD

  • 1

    Use the command (input) on the tag input to update the value. Ex: html5&#xA;<input&#xA;type="text"&#xA;formControlName="nome" &#xA;class="form-control"&#xA;(input)="contaCaracteres()"&#xA;[ngClass]="{'is-invalid': submitted && nome.invalid && (nome.dirty || nome.touched), 'is-valid': (nome.valid && nome.touched ) }">&#xA; Ai in the component, inside the function contaCaracteres(), you can do meuForm.get('nome').value.length and store the return value in another variable. It’s a way for you to always count the characters of a string in the input.

  • 1

    Or, as ta using Formgroup, you can try using the command meuForm.get('nome').value.length on the div that will show the message

Browser other questions tagged

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