1 | initial version |
You can modify the function to return an array of error messages instead of directly outputting them. Then, in your webpage, you can check if the array is empty (i.e., no errors) and display the invoice, or if it contains error messages, display them on the page.
Here is an example implementation:
function FindStringisNonNegInt(q, returnErrors=false) {
var errors = [];
if (q == '') {
errors.push('Input field is empty');
}
else if (isNaN(q)) {
errors.push('Input is not a number');
}
else if (parseInt(q) != q) {
errors.push('Input is not an integer');
}
else if (q < 0) {
errors.push('Input is negative');
}
if (returnErrors) {
return errors;
}
else {
return true;
}
}
// In your webpage code
var input = document.getElementById('input-field').value;
var errors = FindStringisNonNegInt(input, true);
if (errors.length > 0) {
// Display error messages on the page
var errorList = document.createElement('ul');
errors.forEach(function(error) {
var li = document.createElement('li');
li.textContent = error;
errorList.appendChild(li);
});
document.getElementById('error-messages').appendChild(errorList);
}
else {
// Display invoice
// ...
}
In the example code, FindStringisNonNegInt
now returns an array of error messages if the returnErrors
parameter is true
. In your webpage code, you get the input value and call the function with returnErrors
set to true
. If the array of errors is not empty, you create a new ul
element and add li
elements with the error messages to it, then append it to an element on the page (e.g., a div
with id="error-messages"
). If the array is empty, you can proceed with displaying the invoice or performing other actions.