简体   繁体   中英

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>
  • 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" > 

我不确定这是否是导致问题的原因,但我认为class="for-control" required应该是class="for-control" required class="form-control" required

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM