2016-12-16 114 views
0

我不明白爲什麼這個字母數字檢查/驗證不起作用。我已經削減了其他開關選項(全部工作),因爲唯一不起作用的檢查是else if (!(pswRegex.test(inputValue)))。我不是jQuery/Javascript專家,所以我錯過了什麼?字母數字驗證

正則表達式檢查應該允許使用密碼只有如果它由字母(大寫或非大寫)和數字組成。

$(document).ready(function(){ 

    $('.req').on('input', function() { 
     var inputID = $(this).attr('id'); 
     var inputValue = $(this).val(); 
     var valueLenght = $(this).val().length; 

     switch (inputID) { 
      case "psw": 
      var pswRegex = /^[a-zA-Z0-9]+$/; 
      if (valueLenght < 8) { 
       $('#subButton').prop('disabled', true); 
       $('#err' + inputID).show().text("Password must be 8 carachters minimum"); 
      } 
      else if (!(pswRegex.test(inputValue))) { 
       $('#subButton').prop('disabled', true); 
       $('#err' + inputID).show().text("Password must be alphanumeric"); 
      } 
      else { 
       $('#subButton').prop('disabled', false); 
       $('#err' + inputID).hide(); 
      } 
     break; 
     } 
    }); 

}); 

[編輯]:我想實現是顯示錯誤,如果inputValue字符串包含字母或號碼:用戶必須提供字母數字密碼。由於AiorosPeeyush Kushwaha我明白,我不能只用一個正則表達式(至少我對正則表達式的實際知識)實現這一點,所以我改變了我的else if條件這一個:

else if (/^[0-9]+$/.test(inputValue) || /^[a-zA-Z]+$/.test(inputValue)) { 
       $('#subButton').prop('disabled', true); 
       $('#err' + inputID).show().text("Password must be composed by both letters and numbers"); 
      } 

[編輯2]:另一個清潔和優雅的解決方案是由PanterA提供的。只有一個if條件,您可以顯示(僅)一個錯誤說明給用戶,說明密碼必須至少8個carachters長,由至少包含一個大寫字母,一個小寫字母和一個數字組成。

var pswRegex = /^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9]).{8,}$/; 
if (!pswRegex.test(inputValue)) { 
    $('#subButton').prop('disabled', true); 
    $('#err' + inputID).show().text("Password must be at least 8 carachters long and composed by, at least, one capital letter, one lower case letter and one number"); 
} 
+3

似乎在[小提琴](https://jsfiddle.net/w7890gLj/)中工作正常。什麼不適合你?什麼是輸入? – Aioros

+0

@Aioros也許我以錯誤的方式使用了正則表達式'test()',但讓我們假設'var inputValue =「asdwerasd」;' - >這應該從這個檢查'(!(pswRegex。 test(inputValue)))',然後在你的文件中,在控制檯中打印。登錄'正則表達式',對吧?問題是它滑動檢查就好像它總是在你的例子中顯示'ok'並且在我的'else'語句中是'true' – Brigo

+2

@brigo它不應該返回false,'/^[a-zA-Z0- 9] + $ /'意思是「字符或數字」 –

回答

0

此正則表達式可以幫助你:

/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9]).*$/ 

lookahead?=)匹配其括號內沒有任何作爲結果的一部分。在這裏,我們希望正則表達式能夠找到最小的事件發生(.*?),後面跟着我們想強制實施的字符(例如大寫字母)。

所以這個表達式將檢查:

  • 至少有一個大寫字母:(?=.*?[A-Z])
  • 至少一個小寫字母:(?=.*?[a-z])
  • 至少一個數字:(?=.*?[0-9])

查看:https://jsfiddle.net/q7do1woL/

另外,如果您想驗證與正則表達式的字符串的長度,你可以添加一個量詞與最小值:

/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9]).{8,}$/ 

希望它能幫助。

+0

這是很酷的隊友!我從來沒有深入到正則表達式的原因,因爲他們總是嚇到我一點,但這是我的問題最乾淨的工作解決方案!謝謝,我要學習更多關於正則表達式 – Brigo