在ionic/cordova中使用Form模型驗證(w5cValidator)


在構建ionic項目過程中,當我們創建一個類似表單提交的頁面時,可能會對用戶的輸入內容做某些規則驗證,通過后再執行提交處理。

在驗證的過程中,為了提供較好的用戶體驗,可能希望有類似於jquery Validate之類的插件來實現優美的驗證以及提示。

w5cValidator基於angular原有的表單驗證,在原有的基礎上擴展了一些錯誤提示的功能,讓大家不用在每個表單上寫一些提示信息的模板,專心的去實現業務邏輯。

怎樣在ionic項目中使用它,下面來看看:

Stpe1:創建一個項目(此處使用的是tab類型的項目,創建方式可參照我前一篇如何離線創建Ionic1項目

Stpe2:修改項目信息

打開[config.xml]修改id,name,如下圖內容:

Stpe3:引入w5cValidator

下載w5cValidator相關文件,包含w5cValidator.js與w5cValidator.css;這里沒有使用w5cValidator原生的樣式,因為原聲樣式是適用於網頁版bootstrap的,所以我提供了我修改的樣式,以適用於ionicUI。

文件下載地址:http://pan.baidu.com/s/1slgu7fB

下載后將以下兩個文件拷貝到指定目錄

將w5cValidator.css,拷貝到www\css目錄

將w5cValidator.js拷貝到www\s目錄

打開項目www\index.html,引入w5cvalidator的引用

<link href="css/w5cValidator.css" rel="stylesheet">
<script src="js/w5cValidator.js"></script>

 

打開www\js\app.js,將'w5c.validator'加到module引用中。

在app.config事件中添加配置全局屬性和顯示規則,將一下代碼拷貝粘貼到app.js文件中,位置如圖:

代碼如下:

.config(["w5cValidatorProvider", function (w5cValidatorProvider) {

  // 全局配置
  w5cValidatorProvider.config({
    blurTrig   : true,  //光標移除元素后是否驗證並顯示錯誤提示信息
    showError  : showError,  //可以是bool和function,這里使用我們自定義的錯誤顯示方式。
    removeError: removeError   //可以是bool和function,這里使用我們自定義的錯誤移除方式。
  });

  w5cValidatorProvider.setRules({
    email         : {
      required: "輸入的郵箱地址不能為空",
      email   : "輸入郵箱地址格式不正確"
    },
    username      : {
      required      : "輸入的用戶名不能為空",
      pattern       : "用戶名必須輸入字母、數字、下划線,以字母開頭",
      w5cuniquecheck: "輸入用戶名已經存在,請重新輸入"
    },
    password      : {
      required : "密碼不能為空",
      minlength: "密碼長度不能小於{minlength}",
      maxlength: "密碼長度不能大於{maxlength}"
    },
    repeatPassword: {
      required: "重復密碼不能為空",
      repeat  : "兩次密碼輸入不一致"
    },
    number        : {
      required: "數字不能為空"
    },
    customizer    : {
      customizer: "自定義驗證數字必須大於上面的數字"
    },
    dynamicName:{
      required: "動態Name不能為空"
    },
    dynamic       : {
      required: "動態元素不能為空"
    }
  });
}])

添加自定義驗證顯示方式代碼:

位置如圖:

代碼如下:

var showError = function(elem, errorMessages){var $elem = angular.element(elem),
    $group = getParentGroup($elem);

  if (!isEmpty($group)){
    if ($group.hasClass("valid-lr")){
      $group.removeClass("valid-lr");
    }

    if (!$group.hasClass("has-error-lr")){
      $group.addClass("has-error-lr");
    }
  }

  var $next = $group.next();
  if (!$next || !$next.hasClass("form-errors")) {
    $group.after('<div class="form-errors"><div class="form-error">' + errorMessages[0] + '</div></div>');
  }
};

var removeError = function (elem){
  var $elem = angular.element(elem),
    $group = getParentGroup($elem);

  if (!isEmpty($group)){
    if ($group.hasClass("has-error-lr")){
      $group.removeClass("has-error-lr");
    }
  }

  var $next = $group.next();
  if (!$next || $next.hasClass("form-errors")) {
    $next.remove();
  }
};

var getParentGroup = function (elem) {
  if (elem[0].tagName === "FORM" || elem[0].nodeType == 11) {
    return null;
  }
  if (elem && elem.hasClass("item-input")) {
    return elem;
  } else {
    return getParentGroup(elem.parent())
  }
};

var isEmpty = function (object) {
  if (!object) {
    return true;
  }
  if (object instanceof Array && object.length === 0) {
    return true;
  }
  return false;
};

Stpe4:使用

 打開www/js/controllers.js,修改'DashCtrl'為如下代碼:

.controller('DashCtrl', function($scope) {
  $scope.saveEntity = function ($event) {
    //do somethings for bz
    alert("Save Successfully!!!");
  };
})

打開www/templates/tab-dash.html為如下代碼:

<ion-view view-title="w5cValidator Form驗證測試">
  <ion-content class="padding">
    <form role="form" w5c-form-validate="vm.validateOptions" novalidate name="validateForm">
      <ion-list class="list-inset">
        <label class="item item-input">
          <i class="icon ion-android-person placeholder-icon"></i>
          <input type="text"
                 name="name"
                 required=""
                 ng-pattern="/^[A-Za-z]{1}[0-9A-Za-z_]{1,19}$/"
                 ng-model="data.username"
                 placeholder="請輸入用戶名">
        </label>
        <label class="item item-input">
          <i class="icon ion-android-mail placeholder-icon"></i>
          <input type="email"
                 name="email"
                 required=""
                 ng-model="data.email"
                 placeholder="請輸入郵箱">
        </label>
        <label class="item item-input">
          <i class="icon ion-android-lock placeholder-icon"></i>
          <input type="password"
                 name="password"
                 required=""
                 ng-model="data.password"
                 placeholder="請輸入密碼">
        </label>
        <label class="item item-input">
          <i class="icon ion-android-lock placeholder-icon"></i>
          <input type="password"
                 name="repeatPassword"
                 w5c-repeat="password"
                 required=""
                 ng-model="data.repeatPassword"
                 placeholder="請重復輸入密碼">
        </label>
        <button type="submit" class="button button-full icon-right ion-chevron-right button-calm" w5c-form-submit="saveEntity($event)" >提交</button>
      </ion-list>
    </form>
  </ion-content>
</ion-view>

瀏覽器調試,結果如下:

 其他:

感謝why520crazy

其他關於w5cValidator資料,請參考:http://www.ngnice.com/posts/236860ed32d3e8

w5cValidator更多Sample,請參考:http://blog.ngnice.com/angular-w5c-validator/example/index.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM