簡體   English   中英

使用 Javascript 驗證至少 8 個字符和僅字母和數字的組合

[英]Input validation of at least 8 characters and only combinations of letters and numbers using Javascript

我正在對輸入字段進行驗證。 它的驗證是“最少 8 個字符”和“僅包含字母和數字的組合”。

我已經制作了如下腳本,但它仍然不是我想要的。 目前,出現的錯誤是一個一個出現的,而不是一次出現的。

例如,如果我輸入“a12” ,它應該會顯示“最少 8 個字符”錯誤。 如果我輸入“a12”。 "a12@"“最少 8 個字符”錯誤將消失,僅顯示“僅包含字母和數字的組合”錯誤。

錯誤8 character minimum, only contains a combination of letters and numbers

如何解決這個問題?

 $("[name='testing']").on('keyup', function(){ const getValue = $(this).val(); const numbers = /^[A-Za-z0-9]*$/; if(getValue.length < 8){ $('.error').html('<span class="min-char">8 character minimum</span>') if(getValue.match(numbers)){ $('.error.combine-pass').remove() }else{ $('.error').html('<span class="combine-pass">Combination of letters and numbers</span>') } }else{ $('.error.min-char').remove() } })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="text" name="testing"> <div class="error"></div>

我使用正則表達式驗證和 javascript 事件偵聽器來實現用例。

<body>

<input type="text" id="input">
<div id="errorMsg"></div>

<script>
const element = document.getElementById("input");
element.addEventListener("input", validate);

function validate(e) {
let value = e.target.value
const regEx = /^[A-Za-z0-9]*$/
if(regEx.test(value)){
    if(value.length < 8){
    document.getElementById("errorMsg").innerHTML = "8 characters minimum";
    return
    }   
    document.getElementById("errorMsg").innerHTML = "";
} else if(!regEx.test(value)){
    document.getElementById("errorMsg").innerHTML = "only contains a combination of         letters and numbers";
}

}
</script>
</body>
</html>

如果要檢查輸入文本是否包含特殊字符,請使用正則表達式: rg1 = /[^a-z0-9]/gi

如果您想檢查輸入文本是否包含 8 個字符(字母和數字),請使用正則表達式: rg2 = /^[a-z0-9]{8}$/gi

使用這兩個正則表達式,您可以清楚地驗證您的輸入,從而相應地驗證 output。

if(rg1.test(txt)) return "only contains a combination of letters and numbers";
else if(!rg2.test(txt)) return "8 characters minimum";

不需要長度驗證。 如果輸入文本長度正好為 8,則rg2返回true否則返回false

我從長度驗證中取出正則表達式驗證,並將它們總結在文本變量中。

 $("[name='testing']").on('keyup', function(){ const getValue = $(this).val(); const numbers = /^[A-Za-z0-9]*$/; let text = ""; if(getValue.length < 8) { text = "8 character minimum" }else{ $('.error.min-char').remove() } if(getValue.match(numbers)){ $('.error.combine-pass').remove() }else{ text += `${text && ', '}Combination of letters and numbers` } if (text.== "") { $('.error').html(`<span class="combine-pass">${text}</span>`) } })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="text" name="testing"> <div class="error"></div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM