blackHawk
blackHawk

Reputation: 6307

Minlength validation in form is not working

Im trying to understand that If I write validation like this why is it not working and giving me strange result, If Im typing 3 later instead of 4 and move on to next field it runs both div

Name is required

Should be min 4 length

if Im typing 4 laters and move on it displays on should be 4 length

<div class="form-group">
    <lable for="secondName">Second Name</lable>
    
    <input type="text" 
        ngControl='secondName'
        #secondName='ngForm' 
        id="secondName" 
        class="for-control" required
        minlength='4'>
   
    <div *ngIf='secondName.touched'>
    
    <div *ngIf='!secondName.valid'>
        Second Name is required
    </div>

    <div *ngIf='!minlength'>
        min length should be 4
    </div>
</div>

Upvotes: 0

Views: 1083

Answers (2)

nu11p01n73R
nu11p01n73R

Reputation: 26677

  • minlength='4' will not set an angular variable that you can use in the html. I assume that you want to check the length of secondName to be greater that 3, in which case you can write the *ngIf as

    <div *ngIf='secondName.length < 4'>
       min length should be 4
    </div>
    
  • Use [(ngModel)] to bind the secondName instead of ngControl

    <input type="text" [(ngModel)]="secondName" >
    

Upvotes: 1

user4184202
user4184202

Reputation: 64

I'm not sure if this is what is causing the problem, but I believe that class="for-control" required should be class="form-control" required

Upvotes: 0

Related Questions