AngularJS - 表单验证

<form role="form" name="addStaffForm">
    <div ng-init="vm.current.form = addStaffForm" class="form-group"
         ng-class="{ 'has-error' : addStaffForm.email.$invalid && !addStaffForm.email.$pristine }">
        <label>邮箱: </label>
        <input autocomplete='email' type="text" name="email" placeholder="邮箱" ng-model="vm.staff.email"
               class="form-control" ng-pattern="vm.validation.email"
               ng-disabled="vm.currentStaffAction.text=='Update'" required>
        <p ng-show="addStaffForm.email.$error.pattern" class="help-block ng-hide">无效的邮箱地址</p>
    </div>
    <div class="form-group"
         ng-class="{ 'has-error' : addStaffForm.displayName.$invalid && !addStaffForm.displayName.$pristine }">
        <label>名称: </label>
        <input autocomplete='displayName' type="text" name="displayName" placeholder="名称"
               ng-model="vm.staff.displayName" class="form-control" ng-minlength="2"
               ng-maxlength="100" required>

        <p ng-show="!addStaffForm.displayName.$error.pattern && addStaffForm.displayName.$error.minlength"
           class="help-block ng-hide">最小长度为2</p>

        <p ng-show="!addStaffForm.displayName.$error.pattern&&addStaffForm.displayName.$error.maxlength"
           class="help-block ng-hide">最大长度为100</p>
    </div>
    <div class="form-group"
         ng-class="{ 'has-error' : addStaffForm.lastName.$invalid && !addStaffForm.lastName.$pristine }">
        <label>角色:</label>
        <select class="form-control" ng-model="vm.staff.auth.role"
                ng-options="role.value as role.name for role in vm.roles">
            <option value="">-- 选择角色 --</option>
        </select>
    </div>
    <div class="modal-footer text-right">
        <button class="btn btn-primary" ng-click="$dismiss()">
            <i class="btn-icon glyphicon glyphicon-remove"></i>
            <span>{{ 'COMMON_CANCEL' | translate }}</span>
        </button>
        <button class="btn btn-primary" ng-click="$close(vm.staff)" ng-disabled="vm.current.form.$invalid">
            <i class="btn-icon glyphicon glyphicon-ok"></i>
            <span>{{ 'COMMON_CONFIRM' | translate }}</span>
        </button>
    </div>
</form>
vm.validation = {
    email: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
};
  • required 必填
  • addStaffForm.email.$invalid 是否验证未通过,未通过为true
  • addStaffForm.email.$pristine 输入框没有使用为true
  • addStaffForm.email.$error.pattern 匹配正则 ng-pattern=“vm.validation.email”
  • addStaffForm.displayName.$error.minlength 最小长度 ng-minlength=“2”
  • addStaffForm.displayName.$error.maxlength 最大长度 ng-maxlength=“100”
  • vm.current.form.$invalid 是否验证未通过,未通过为true

猜你喜欢

转载自blog.csdn.net/seaalan/article/details/86166977
今日推荐