I am writing this code to save or update employee data in an object. If the ID number field is empty, then it is a new employee and a random employee ID will be generated and if an ID is provided, then the ID will be searched and the record will be updated. But I need to validate that the ID input is a number before searching. The regular expression is allowing letters to pass through but I want it to alert "ID must be a number" and return false. The code is below:
//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>