angularJS表单验证

1、module中引入ngMessages

2、页面代码

<form name="createVolumeForm"  novalidate>
                    <div class="control-group" >
                        <label class="control-label">名称:</label>
                        <div class="controls">
                            <input type="text" class="form-controls" name="name" ng-model="volumeForm.name"  placeholder="请输入云硬盘名称" ng-pattern="/^[a-zA-Z0-9_]{1,100}$/" required />
                        <div class="error-messages" ng-if="interacted(createVolumeForm.name)" ng-messages="createVolumeForm.name.$error" style="color: #e9322d;">
                          <div ng-message="required" class="volume-form-name-error">必填项</div>
                          <div ng-message="pattern" class="volume-form-name-error">请输入字符,允许有英文字母、数字和下划线</div>
                        </div> 
                        </div>
                    </div>
                     <div class="control-group">
                        <label class="control-label">配置:</label>
                        <div class="controls">
                            <input type="text" class="form-controls" name="size" ng-model="volumeForm.size" placeholder="请输入云硬盘大小" ng-pattern="/^[0-9]$/" required />
                        </div>
                        <div class="error-messages"  ng-if="interacted(createVolumeForm.size)" ng-messages="createVolumeForm.size.$error" style="color: #e9322d;">
                          <div ng-message="required" class="volume-form-size-error">必填项</div>
                          <div ng-message="pattern" class="volume-form-size-error">请输入大于或等于零的数字</div>
                        </div> 
                    </div>
                    <div class="control-group">
                        <label class="control-label">描述信息:</label>
                        <div class="controls">
                            <textarea type="text" class="form-controls volume-text " name="description" style="height:50px;" ng-model="volumeForm.description" placeholder="请输入描述信息" />
                        </div>
                    </div>
            </form>

注意,form和input元素要有name属性

3.controller

$scope.submitted=false;
 $scope.interacted=function(field){
    return self.submitted||field.$dirty;
  }

相关推荐