Angular 5 ngx-bootstrap form validation

蹲街弑〆低调 提交于 2019-12-04 06:04:45

It'll work by adding a class="was-validated" to the outer most div as per documentation: link to bootstrap form validation. This will initiate the validation on your fields. Also, remember to flag your inputs with required and turn of default html validation by passing the form a novalidate

Example of working code:

<div class="container" class="was-validated">
  <form [formGroup]="regForm" novalidate (ngSubmit)="submitForm(regForm.value)">
    <div class="row justify-content-center">
      <div class="form-group col-6">
        <label class="col-12 col-form-label" for="email">Email</label>
        <input type="email" placeholder="Email address" class="form-control form-control-lg col-12" id="email" [formControl]="regForm.controls['email']"
          required>
        <div class="invalid-feedback">
          Please provide a valid email.
        </div>
      </div>
    </div>

    <div class="row justify-content-center">
      <div class="form-group col-6">
        <label class="col-12 col-form-label" for="password">Password</label>
        <input type="password" placeholder="Password" id="password" class="form-control form-control-lg col-12" [formControl]="regForm.controls['password']" required>
        <div class="invalid-feedback">
          Please provide a password.
        </div>
      </div>
    </div>

    <div class="row justify-content-center">
      <div class="form-group col-6">
        <button type="submit" class="btn btn-outline-secondary btn-block col-12">Sign in</button>
      </div>
    </div>
  </form>
</div>

You could - and probably should, add the class="was-validated" programmatically, not hardcode it like i did.

If you have any trouble with this, feel free to comment my post - and i will update my answer.

Props to @ChrisEenberg on this. If you want to have each field be validated as the user types, put the was-validated on the form-group <div class="form-group row" [ngClass]="{'was-validated': (categoryVar.touched || categoryVar.dirty) && !categoryVar.valid }">

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!