Ask Your Question
2

How can I show the errors from the "function FindStringisNonNegInt(q, returnErrors=false)" on my webpage instead of my invoice?

asked 2022-10-27 11:00:00 +0000

huitzilopochtli gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2021-05-02 15:00:00 +0000

devzero gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-10-27 11:00:00 +0000

Seen: 13 times

Last updated: May 02 '21