Angular 2 form validation, minLength validator is not working

前端 未结 7 1645
旧巷少年郎
旧巷少年郎 2021-02-06 21:04

I have following Angular 2 form:


    
&l
相关标签:
7条回答
  • 2021-02-06 21:11
    field: ['', Validators.compose([Validators.required, Validators.minLength(8)])]
    

    This only works with multiple validators.

    0 讨论(0)
  • 2021-02-06 21:17

    This really caught me out as well as I matched the key in my markup to what I had in code which is incorrect.

    Sample Code

    password1: ['', [Validators.required, Validators.minLength(8)]],

    Sample Markup

    *ngIf="registrationRequest.get('password1').hasError('minlength')"

    Note in the code it's minlength entirely in lower case.

    0 讨论(0)
  • 2021-02-06 21:18

    This worked for me for password validation.

    <input type="password" class="form-control" name="password" placeholder="Password" [(ngModel)]="register.password" #password="ngModel" minlength="6" required>
    
    0 讨论(0)
  • 2021-02-06 21:24

    I had the same problem where I wanted to validate a number field that contained the year, so I used Validators.maxLength(4) to make sure someone does not accidently type 5 numbers for a year. Turns out when you set the input type to number:

    <input type="number" formControlName='year'>
    

    then maxLength does not "work" anymore. Which actually makes sense if you think about it for half a second.

    So I changed my date input to:

    year: [null, [Validators.required, Validators.min(1990), Validators.max(2050)]],
    

    Which is the right approach when working with a number field.

    0 讨论(0)
  • 2021-02-06 21:27

    <div *ngIf = "password.errors.minLength && !password.errors.required" class = "alert alert-danger">
    <span>Password should contain 6 characters</span>
    </div> 

    minLength must be lowercase minlength

    0 讨论(0)
  • 2021-02-06 21:36

    I was facing the same issue but after so many research I got a solution with this, Please use minlength insted of minLength Here is the example.

    <div *ngIf = "password.errors.minlength && !password.errors.required" class = "alert alert-danger">
          <span>Password should contain 6 characters</span>
        </div> 
    

    Instead of

    <div *ngIf = "password.errors.minLength && !password.errors.required" class = "alert alert-danger">
      <span>Password should contain 6 characters</span>
    </div> 
    

    Hope this will help someone, Thanks

    0 讨论(0)
提交回复
热议问题