我不明白爲什麼這個字母數字檢查/驗證不起作用。我已經削減了其他開關選項(全部工作),因爲唯一不起作用的檢查是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
字符串包含僅字母或僅號碼:用戶必須提供字母數字密碼。由於Aioros和Peeyush 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");
}
似乎在[小提琴](https://jsfiddle.net/w7890gLj/)中工作正常。什麼不適合你?什麼是輸入? – Aioros
@Aioros也許我以錯誤的方式使用了正則表達式'test()',但讓我們假設'var inputValue =「asdwerasd」;' - >這應該從這個檢查'(!(pswRegex。 test(inputValue)))',然後在你的文件中,在控制檯中打印。登錄'正則表達式',對吧?問題是它滑動檢查就好像它總是在你的例子中顯示'ok'並且在我的'else'語句中是'true' – Brigo
@brigo它不應該返回false,'/^[a-zA-Z0- 9] + $ /'意思是「字符或數字」 –