Bootstrap表单验证无法在angular2

时间:2017-04-07 10:53:26

标签: forms validation angular angular2-forms twitter-bootstrap-form

我已在angular2应用程序中实现了bootstrap表单验证,并且即使在正确使用bootstrap表单验证指令之后,某些表单元素也未得到验证。当我尝试检查代码时,我发现“has-error”类没有出现在表单字段中。

这是我的表单代码:

<form id="emailForm" 
                                #emailForm= "ngForm" 
                                novalidate="novalidate" 
                                [saBootstrapValidator]="validatorOptions">

                                    <!-- widget content -->
                                    <div class="widget-body">
                                        <!--template Name -->
                                        <fieldset>
                                            <div class="form-group">
                                                <div class="row">
                                                    <section class="col-sm-12 col-md-10">
                                                        <strong class="control-label">Name</strong><label class="required"></label>
                                                        <input class="form-control" 
                                                        placeholder="Enter template name" 
                                                        type="text" 
                                                        value="{{message.name}}"
                                                        name="templateName" [(ngModel)]="composeModel.Name">
                                                    </section>
                                                    <section class="col-sm-12 col-md-2">
                                                        <label for="select2-multiple">
                                                        <strong>Category</strong></label>
                                                        <select 
                                                        style="width:100%" 
                                                        class="form-control select2" 
                                                        name="category">
                                                            <option *ngFor = "let category of templateCategories" value="{{category.Id}}">{{category.Name}}</option>
                                                    </select>

                                                    </section>
                                                </div>
                                            </div>
                                        </fieldset>


                                        <!--Description -->
                                        <fieldset>
                                            <div class="form-group">
                                                <div class="row">
                                                    <section class="col-sm-12 col-md-12 ">
                                                        <strong>Description</strong>
                                                        <textarea class="form-control" name="review" rows="2" placeholder="Enter a brief summary that decribes the puropose of this template "  [(ngModel)]="composeModel.Description"></textarea>
                                                    </section>
                                                </div>
                                            </div>
                                        </fieldset>


                                        <!-- To -->
                                        <fieldset>
                                            <div class="form-group">
                                                <div class="row">
                                                    <section class="col-md-12">
                                                        <strong class="control-label">To</strong><label class="required"></label>
                                                        <popover-content #multSelectContent>
                                                            <span style="color: #3276B1">Hold ctrl-key to select multiple emails<br /> Start typing to search for email</span>
                                                        </popover-content>
                                                        <a (click)="(null)" 
                                                        class="fa fa-question-circle" 
                                                        popoverPlacement="top" 
                                                        [popoverOnHover]="true" 
                                                        data-html="true" 
                                                        popoverTitle="Multiple Selection" 
                                                        [popover]="multSelectContent"></a>

                                                        <div class="boxed">
                                                            <select
                                                            multiple select2 style="width:100%" 
                                                            data-select-search="true" 
                                                            class="form-control select2-multiple"
                                                            name="emailTo">

                                                        <optgroup label="Responsible Parties">
                                                            <option value="1"> sunny.orlaf@smartadmin.com</option>
                                                            <option value="2"> rachael.hawi@smartadmin.com</option>
                                                            <option value="3"> michael.safiel@smartadmin.com</option>
                                                        </optgroup>
                                                        <optgroup label="Evaluator">
                                                            <option value="alex.jones@infowars.com"> alex.jones@infowars.com</option>
                                                            <option value="oruf.matalla@gmail.com"> oruf.matalla@gmail.com</option>
                                                            <option value="hr@smartadmin.com"> hr@smartadmin.com</option>
                                                            <option value="IT@smartadmin.com"> IT@smartadmin.com</option>
                                                        </optgroup>
                                                          <optgroup label="Informed Parties">
                                                            <option value="alex.jones@infowars.com"> alex1.jones@infowars.com</option>
                                                            <option value="oruf.matalla@gmail.com"> oruf1.matalla@gmail.com</option>
                                                            <option value="hr@smartadmin.com"> hr1@smartadmin.com</option>
                                                            <option value="IT@smartadmin.com"> IT1@smartadmin.com</option>
                                                        </optgroup>
                                                    </select>

                                                        </div>
                                                    </section>
                                                </div>
                                            </div>
                                        </fieldset>

                                        <!-- CC  -->
                                        <fieldset>
                                            <div class="form-group">
                                                <div class="row">
                                                    <section class="col-sm-12 col-md-6">
                                                        <label><strong>CC</strong></label>
                                                        <popover-content #multSelectContent1>
                                                            <span style="color: #3276B1">Hold ctrl-key to select multiple emails<br /> Start typing to search for email</span>
                                                        </popover-content>
                                                        <a (click)="(null)" class="fa fa-question-circle" popoverPlacement="top" [popoverOnHover]="true" data-html="true" popoverTitle="Multiple Selection" [popover]="multSelectContent1"></a>

                                                        <div class="boxed">
                                                            <select multiple select2 style="width:100%" data-select-search="true" class="select2">
                                                        <optgroup label="Responsible Parties">
                                                            <option value="sunny.orlaf@smartadmin.com">sunny.orlaf@smartadmin.com</option>
                                                            <option value="rachael.hawi@smartadmin.com">rachael.hawi@smartadmin.com</option>
                                                            <option value="michael.safiel@smartadmin.com">michael.safiel@smartadmin.com</option>
                                                        </optgroup>
                                                        <optgroup label="Evaluator">
                                                            <option value="alex.jones@infowars.com">alex.jones@infowars.com</option>
                                                            <option value="oruf.matalla@gmail.com">oruf.matalla@gmail.com</option>
                                                            <option value="hr@smartadmin.com">hr@smartadmin.com</option>
                                                            <option value="IT@smartadmin.com">IT@smartadmin.com</option>
                                                        </optgroup>
                                                           <optgroup label="Informed Parties">
                                                            <option value="alex.jones@infowars.com">alex1.jones@infowars.com</option>
                                                            <option value="oruf.matalla@gmail.com">oruf1.matalla@gmail.com</option>
                                                            <option value="hr@smartadmin.com">hr1@smartadmin.com</option>
                                                            <option value="IT@smartadmin.com">IT1@smartadmin.com</option>
                                                        </optgroup>
                                                    </select>
                                                        </div>

                                                    </section>



                                                    <!-- BCC  -->

                                                    <section class="col-sm-12 col-md-6">
                                                        <label><strong>BCC</strong></label>
                                                        <popover-content #multSelectContent1>
                                                            <span style="color: #3276B1">Hold ctrl-key to select multiple emails<br /> Start typing to search for email</span>
                                                        </popover-content>
                                                        <a (click)="(null)" class="fa fa-question-circle" popoverPlacement="top" [popoverOnHover]="true" data-html="true" popoverTitle="Multiple Selection" [popover]="multSelectContent1"></a>

                                                        <div class="boxed">
                                                            <select multiple select2 style="width:100%" data-select-search="true" class="select2">
                                                        <optgroup label="Responsible Parties">
                                                            <option value="sunny.orlaf@smartadmin.com">sunny.orlaf@smartadmin.com</option>
                                                            <option value="rachael.hawi@smartadmin.com">rachael.hawi@smartadmin.com</option>
                                                            <option value="michael.safiel@smartadmin.com">michael.safiel@smartadmin.com</option>
                                                        </optgroup>
                                                        <optgroup label="Evaluator">
                                                            <option value="alex.jones@infowars.com">alex.jones@infowars.com</option>
                                                            <option value="oruf.matalla@gmail.com">oruf.matalla@gmail.com</option>
                                                            <option value="hr@smartadmin.com">hr@smartadmin.com</option>
                                                            <option value="IT@smartadmin.com">IT@smartadmin.com</option>
                                                        </optgroup>
                                                           <optgroup label="Informed Parties">
                                                            <option value="alex.jones@infowars.com">alex1.jones@infowars.com</option>
                                                            <option value="oruf.matalla@gmail.com">oruf1.matalla@gmail.com</option>
                                                            <option value="hr@smartadmin.com">hr1@smartadmin.com</option>
                                                            <option value="IT@smartadmin.com">IT1@smartadmin.com</option>
                                                        </optgroup>
                                                    </select>
                                                        </div>

                                                    </section>
                                                </div>
                                            </div>
                                        </fieldset>

                                        <!--Subject -->
                                        <fieldset>
                                            <div class="form-group">
                                                <div class="row">
                                                    <section class="col-md-12 ">
                                                        <label><strong>Subject</strong></label>
                                                        <popover-content #multSelectContent>
                                                            <span style="color: #3276B1">Hold ctrl-key to select multiple emails<br /> Start typing to search for email</span>
                                                        </popover-content>
                                                        <a (click)="(null)" 
                                                        class="fa fa-question-circle" 
                                                        popoverPlacement="top" 
                                                        [popoverOnHover]="true" 
                                                        data-html="true" 
                                                        popoverTitle="Multiple Selection" 
                                                        [popover]="multSelectContent"></a>

                                                        <div class="boxed">
                                                            <select
                                                            multiple select2 style="width:100%" 
                                                            data-select-search="true" 
                                                            class="form-control select2-multiple"
                                                            name="emailTo"
                                                            placeholder = "Email Subject">

                                                        <optgroup label="Evaluation type title">
                                                        </optgroup>
                                                        <optgroup label="Topic">
                                                            <option value="topic1">topic1</option>
                                                            <option value="topic2">topic2</option>
                                                        </optgroup>
                                                          <optgroup label="Question">
                                                            <option value="question1">Question1</option>
                                                            <option value="question2">Question2</option>
                                                        </optgroup>
                                                        <optgroup label="Response">
                                                            <option value="response1">response1</option>
                                                            <option value="response2">response2</option>
                                                        </optgroup>
                                                        <optgroup label="Value">
                                                            <option value="value1">value1</option>
                                                            <option value="value2">value2</option>
                                                        </optgroup>
                                                        <optgroup label="Today's Date'">
                                                            <option value="4.5.2017">4.5.2017</option>
                                                        </optgroup>
                                                    </select>

                                                        </div>

                                                        <!--<input class="form-control" placeholder="Email Subject" type="text" value="{{message.subject}}">-->
                                                    </section>
                                                </div>
                                            </div>
                                        </fieldset>

                                        <!--Message -->
                                        <fieldset>
                                            <div class="form-group">
                                                <div class="row">
                                                    <section class="col-md-12 ">
                                                        <strong>Message</strong><label class="control-label required"></label>
                                                        <div class="summernote form-control" name="messageBody" [summernote]="{height: 120}"></div>
                                                    </section>
                                                </div>
                                            </div>
                                        </fieldset>
                                        <!--Action  buttons -->
                                        <fieldset>
                                            <div class="smart-form pull-right">
                                                <section class="col-md-12 p ">
                                                    <div class="btn-group">
                                                        <button class="btn btn-sm btn-primary" type="button"><i class="fa fa-times"></i> Cancel </button>
                                                    </div>
                                                    <div class="btn-group">
                                                        <button class="btn btn-sm btn-success" type="submit" [disabled]="!emailForm.invalid" (click)="onSubmit()"><i class="fa fa-save"></i> Save </button>
                                                    </div>
                                                </section>

                                            </div>
                                        </fieldset>
                                    </div>
                                    <!-- end widget content -->
                                </form>

这就是我的表单出现的方式: enter image description here

这是我的component.ts代码:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { OutlookService, Message } from '../shared';
import { EmailComposeService } from '../compose/compose.service';
import { EmailComposeModal } from '../../data-model/email-compose';
declare var $: any;

@Component({
  selector: 'sa-compose',
  templateUrl: 'compose.component.html',
})
export class ComposeComponent implements OnInit {

  public $: any;


  validatorOptions = {
    feedbackIcons: {
      valid: 'glyphicon glyphicon-ok',
      invalid: 'glyphicon glyphicon-remove',
      validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
      templateName: {
        validators: {
          notEmpty: {
            message: 'The template name is required and cannot be empty'
          }
        }
      },
      emailTo: {
        validators: {
          notEmpty: {
            message: 'The sender email is required and cannot be empty'
          }
        }
      },
      messageBody: {
        validators: {
          callback: {
            message: 'The content is required and cannot be empty',
            callback: function (value, validator, $field) {
              var code = $('[name="messageBody"]').summernote('code');
              // <p><br></p> is code generated by Summernote for empty content
              return (code !== '' && code !== '<p><br></p>');
            }
          }
        }
      }
    }
  };

  public templateName: String = '';


  public message: Message;
  public carbonCopy: boolean = false;
  public blindCarbonCopy: boolean = false;
  public attachments: boolean = false;

  public sending: boolean = false;
  templateCategories: any;

  constructor(private route: ActivatedRoute,
    private router: Router,
    private service: OutlookService, private composeservice: EmailComposeService) {

  }

  ngOnInit() {
    this.message = new Message({})
    this.composeservice.getTempateCategory(1, JSON.parse(localStorage.getItem('currentUser')).access_token).subscribe(data => {
      this.templateCategories = data;
      this.composeModel.CategoryId = data[0].Id;
    });

  }

  isUpdate: boolean = false;

  isDelete: boolean = false;

  isCreateTemplate: boolean = false;

  submitted = false;

  composeModel = new ComposeClass();



  onSubmit() {
    //this.uploadImage();

    if (this.isUpdate) {
      let composePutData: EmailComposeModal = {
        Id: +this.composeModel.Id,
        IndustryId: +this.composeModel.IndustryId,
        CategoryId: +this.composeModel.CategoryId,
        Name: this.composeModel.Name,
        Content: this.composeModel.Content,
        Description: this.composeModel.Description,
        Status: this.composeModel.Status,
        CreatedBy: this.composeModel.CreatedBy,
        CreateTimestamp: this.composeModel.CreateTimestamp,
        ModifiedBy: localStorage.getItem('selectedRolesID'),
        ModifiedTimestamp: new Date(),
        DataStateFlag: this.composeModel.DataStateFlag
      }

      if (this.isDelete) {
        this.composeservice.updateTemplate(composePutData, JSON.parse(localStorage.getItem('currentUser')).access_token).subscribe(res => {
          if (res.status === 200) {
            this.isUpdate = false;
            this.isDelete = false;
            this.composeModel = new ComposeClass();
            this.isCreateTemplate = false;
            $('.divMessageBox').hide();
          }
        });
      } else {
        this.composeservice.updateTemplate(composePutData, JSON.parse(localStorage.getItem('currentUser')).access_token).subscribe(res => {
          if (res.status === 200) {
            this.isUpdate = false;
            this.composeModel = new ComposeClass();
            this.isCreateTemplate = false;
            $('.divMessageBox').hide();
          }
        });
      }

    } else {
      var code = $('[name="messageBody"]').summernote('code');
      let postdata: EmailComposeModal = {
        IndustryId: 1,
        CategoryId: +this.composeModel.CategoryId,
        Name: this.composeModel.Name,
        Content: code,
        Description: this.composeModel.Description,
        Status: "Active",
        CreatedBy: localStorage.getItem('selectedRolesID'),
        CreateTimestamp: new Date(),
        DataStateFlag: "I",
        "ModifiedBy": null,
        "ModifiedTimestamp": null
      }

      this.submitted = true;
      this.composeservice.createTemplate(postdata, JSON.parse(localStorage.getItem('currentUser')).access_token).subscribe(res => {
        if (res.status === 200) {
          this.composeModel = new ComposeClass();
          this.isCreateTemplate = true;
          $('.nav-tabs a[href="#a1"]').tab('show');
          $('[name="messageBody"]').summernote('reset');
        }
      })
    }
  }

}

export class ComposeClass {
  constructor(
    public Id?: number,
    public IndustryId?: number,
    public CategoryId?: number,
    public Name?: string,
    public Content?: string,
    public Description?: string,
    public Status?: string,
    public CreatedBy?: string,
    public CreateTimestamp?: Date,
    public ModifiedBy?: string,
    public ModifiedTimestamp?: Date,
    public DataStateFlag?: string
  ) {

  }
}

第一个输入元素正在验证,但是选择字段和summernote字段未经过验证。

1 个答案:

答案 0 :(得分:0)

我终于解决了。 如果将排除的:[&#39;:disabled&#39;]添加到validatorOptions,则select2验证将起作用。它检查空值。

关于summernote,将以下代码添加到onInit()解决了这个问题:

$(".summernote")
.on('summernote.change', function(customEvent, contents, $editable) {
// Revalidate the content when its value is changed by Summernote
 $('#emailForm').bootstrapValidator('revalidateField', 'content');

希望这有帮助!