2013-09-30 13 views
22
link: function(scope, elm, attrs, ctrl) { 
     ctrl.$parsers.unshift(function(viewValue) { 

      scope.pwdValidLength = (viewValue && viewValue.length >= 8 ? 'valid' : undefined); 
      scope.pwdHasLetter = (viewValue && /[A-z]/.test(viewValue)) ? 'valid' : undefined; 
      scope.pwdHasNumber = (viewValue && /\d/.test(viewValue)) ? 'valid' : undefined; 

      if(scope.pwdValidLength && scope.pwdHasLetter && scope.pwdHasNumber) { 
       ctrl.$setValidity('pwd', true); 
       return viewValue; 
      } else { 
       ctrl.$setValidity('pwd', false);      
       return undefined; 
      } 

     }); 
    } 

http://jsfiddle.net/adamdbradley/Qdk5M/

は、どのようにパスワードの検証は行われていますか? $ parser.unshiftは何をしますか?どのようなテスト(viewValue).....の使用ですか? 私は以下

答えて

60

がある..私はangularJSに新しいです... は、それが検証を行っているかのステップバイステップで私を導いてください...

をAngularJsメインのサイトを参照しているが、任意のものを理解することができませんでしたステップバイステップの説明。ドキュメントが本当に良いことに注意してください。the formsのページとthe $parsersのページがあなたが探しているものです。

link: function(scope, elm, attrs, ctrl) { 
    /** 
    * This function is added to the list of the $parsers. 
    * It will be executed the DOM (the view value) change. 
    * Array.unshift() put it in the beginning of the list, so 
    * it will be executed before all the other 
    */ 
    ctrl.$parsers.unshift(function(viewValue) { 

     scope.pwdValidLength = (viewValue && viewValue.length >= 8 ? 'valid' : undefined); // Check the length of the string 
     scope.pwdHasLetter = (viewValue && /[A-z]/.test(viewValue)) ? 'valid' : undefined; // Check if the string contains letter. RegExp.test() simply returns a boolean if the string matches the regex. 
     scope.pwdHasNumber = (viewValue && /\d/.test(viewValue)) ? 'valid' : undefined; // Check if the string contains digit. Same remark. 

     if(scope.pwdValidLength && scope.pwdHasLetter && scope.pwdHasNumber) { // If all is good, then… 
      ctrl.$setValidity('pwd', true); // Tell the controlller that the value is valid 
      return viewValue; // Return this value (it will be put into the model) 
     } else { // … otherwise… 
      ctrl.$setValidity('pwd', false); // Tell the controlller that the value is invalid 
      return undefined; // When the value is invalid, we should return `undefined`, as asked by the documentation 
     } 

    }); 
} 
+1

グレート答えをコーディングハッピー:しかし、私はあなたにもこの便利なブログを読むべきだと思います。受け入れられるべきである。 – hitokiri82

+0

$ parsersは配列です(つまり、標準のjavascript型で、Angularに固有のものではありません)。 unshiftはJavascript Arrayプロトタイプのネイティブメソッドなので、 "Array.unshift()のこの答えのコメントはリストの先頭に入れます..." 初心者が混乱する可能性があるので、それは重要な違いです角度のあるものとネイティブJSのものとの間にあります。 – dudewad

関連する問題