How to add a more detialed message upon Submit

I believe the code below generates this message: “Value must be greater than or equal to 1” when a zero is entered in that Form Field and Submit is selected. Correct?

<input id="myField" name="set_p" type="number" min="1" placeholder="" class="form-control input-md" autocomplete="off" required>

That message display via the browser, correct?

How could I change the message, so that upon Submit, if a Zero is entered a more detailed message appears? Via Javascript?

I look forward to any assistance.

Yes, that message is generated by the browser.

To display your own messages:

HTML:

<form onsubmit="return validate()" action="" method="post">
  <input id="myField" name="set_p" placeholder="" class="form-control input-md" autocomplete="off" required>
  <button>Submit</button>
  <p id="myMessage"></p>
</form>

JavaScript:

function validate(){  
  let v = document.getElementById("myField").value;
  let m = document.getElementById("myMessage");
  
  if(isNaN(v)) m.innerText = "Please enter a number";
  else if(v < 0) m.innerText = "Please enter a positive number";
  else if(v == 0) m.innerText = "Zero is not allowed";
  else return true;   // form will be submitted
  
  return false;   // form will not be submitted
}

Note that JavaScript allows decimal numbers.

3 Likes

Just trying out an alternative approach.

<form id='my-form' action="" method="post">
  <label for='numField'>Number:</label>
  <input 
    type='number' 
    id="numField"
    class="form-control input-md" 
    name="numField" 
    placeholder="Enter a number" 
    autocomplete="off"
  >
  <button>Submit</button>
  <p id="error"></p>
</form>

If the html isn’t tinkered with by the user, the browser will prevent letters from being entered.

// separate function to check number inputs
function numCheck (num) {
  switch (true) {
    case (num.trim() === '' || isNaN(num)):
      return 'Please enter a number';
    case (num == 0):
      return 'Please enter a value larger than zero';
    case (num < 0):
      return 'Please enter a positive value';
    default:
      return false;
  }
}

function validate(form) {
  // can access field by name through form.elements
  const num = form.elements.numField.value;
  const errorOutput = form.querySelector('#error');
  const errorMsg = numCheck(num)
  
  if (errorMsg) {
    errorOutput.textContent = errorMsg;
    return false; // exit here
  }
  
  form.submit() // all good
}

const form = document.querySelector('#my-form')

// alternative to an inline onSubmit
form.addEventListener('submit', (event) => {
  event.preventDefault();
  validate(event.target);  // event.target is the submitted form
})

Obviously not as straightforward as Archibald’s approach.

Edit: I do think ‘Value must be greater than or equal to 1’ says it all though

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.