簡體   English   中英

Javascript 代碼對輸入字段中輸入的用戶名執行 split()

[英]Javascript code to perform split() on user names entered in input field

我的 HTML 表單中有一個字段,用戶應該輸入他的全名。 我需要可以調用.split function 的 javascript 代碼,以確保在字段中輸入的兩個單詞之間至少有一個空格進行驗證。 拆分 function 應計算單詞之間的空格數,如果為零,則用戶輸入了單個名稱單詞並應顯示錯誤,如果其為一個及以上,則用戶已通過驗證。 這個讓我大吃一驚,誰能幫我寫代碼

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div class="container">
    <div class="form">
        <label class="accent-1">Enter Your Full Names</label>
        <input type="text" class="form-control" id="mytext">
    </div>
</div>
<script>
    //we are going to scan if user attempted to enter one name using split
    //get the field
    let field=document.getElementById("mytext");
    let y=field.value;
    //javscript split function to fetch substrings into array and check for spaces

</script>
</body>

您可以獲取value拆分字符串(值)並檢查長度。 根據情況進行檢查。

 const button = document.querySelector("button"); const input = document.querySelector("input"); const error = document.querySelector("div#error"); button.addEventListener("click", e => { const data = input.value.split(" "); if (data.length <= 1) { error.textContent = "Error"; // Do when there is only single word - REJECTED CASE } else { error.textContent = ""; // Do when there is more than a word - ACCEPTED CASE } })
 div#error{ color: red; font-size: 12px; }
 <div class="container"> <div class="form"> <label class="accent-1">Enter Your Full Names</label> <input type="text" class="form-control" id="mytext"> <div id="error"></div> <button> submit </button> </div> </div>

暫無
暫無

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

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