簡體   English   中英

如何使用正則表達式檢查輸入是否為數字?

[英]how do I check if input is a number using regular expression?

我正在編寫此代碼來保存或更新對象中的員工數據。 如果 ID 號字段為空,則為新員工,將生成隨機員工 ID,如果提供 ID,則搜索 ID 並更新記錄。 但是我需要在搜索之前驗證輸入的 ID 是一個數字。 正則表達式允許字母通過,但我希望它提醒“ID 必須是數字”並返回 false。 代碼如下:

 //Javascript Code const recordCollection = { } function userRecords() { let idNum = document.getElementById('idNum').value; let firstName = document.getElementById('firstName').value; let lastName = document.getElementById('lastName').value; let age = document.getElementById('age').value; let department = document.getElementById('department').value; let role = document.getElementById('jobRole').value; let level = document.getElementById('level').value; let demo = document.getElementById('demo'); let regex = /^[0-9]+$/; // generate employer id if (idNum === "") { //if there is no id, generate a four(4)-digit number id for the employer idNum = Math.floor(Math.random() * (9999 - 1000 + 1)) + 1000; } else if (!idNum.match(regex)) { //check if id is a number alert("ID must be a Number"); return false; } else if (idNum.length !== 4) { //check if id is equal to 4 alert("ID must be four(4) numbers"); return false; } } //create or update a record // recordCollection["id"] = idNum; recordCollection["First Name"] = firstName; recordCollection["Last Name"] = lastName; recordCollection["age"] = age; recordCollection["department"] = department; recordCollection["Job Role"] = role; recordCollection["Level"] = level; demo.innerHTML = JSON.stringify(recordCollection, null, 2); return demo;
 <!-- HTML code--> <aside> <div> <div> <h3>Add or Update User Information</h3> <div> <label>ID No.</label> <input type="number" id="idNum"> </div> <div> <label>First Name</label> <input type="text" id="firstName"> </div> <div> <label>Last Name</label> <input type="text" id="lastName"> </div> <div> <label>Age</label> <input type="number" id="age"> </div> <div> <label>Department</label> <input type="text" id="department"> </div> <div> <label>Job Role</label> <input type="text" id="jobRole"> </div> <div> <label>Level</label> <input type="text" id="level"> </div> <div> <button onclick="userRecords();">Submit</button> </div> </div> </div> </aside> <section> <h3>Result Below</h3> <pre id="demo"></pre> </section>

String.match 返回一個Array

我認為您正在尋找的是Regex .test(String)

const someIds = ['abcd', '12as', '1234', '123', '123a45', '12345'];
const regex = /^[0-9]+$/;

someIds.forEach(id => console.log("id is valid: ", regex.test(id)))

你也可以擴展你的正則表達式只接受四個數字:

/^[0-9]{4}$/

暫無
暫無

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

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