我编写此代码是为了保存或更新对象中的员工数据。如果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返回一个数组。
我想你要找的是Regex.test(字符串(
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}$/