Monique Sullivan
Monique Sullivan

Reputation: 43

Javascript multiple fields validating

First, I have to validate that id and password textboxes are not empty(That one's working). Then I have to validate on the same form that id on textbox needs to be a number and also a number between 3000 and 3999 (That one doesn't work). Any ideas on what's wrong with my code?

function validatefunctions() {
  if (document.getElementById('idtb').value === '') {
    alert('You need to enter a Customer ID');
    return false;
  }

  if (document.getElementById('pwtb').value === '') {
    alert('Please enter your password');
    return false;
  }
  var custID;
  custID = document.getElementsByName("idtb").valueOf();

  if (custID !== isNan) {
    alert("Customer ID needs to be numeric");
    return false;
  }
  if (custID < 3000) {
    alert("ID must be above 3000");
    return false;
  }
  if (custID > 3999) {
    alert("ID must be below 3999");
    return false;
  }
}

Upvotes: 3

Views: 89

Answers (2)

ankitkanojia
ankitkanojia

Reputation: 3122

function validatefunctions() {
  if (document.getElementById('idtb').value === '') {
    alert('You need to enter a Customer ID');
    return false;
  }

  if (document.getElementById('pwtb').value === '') {
    alert('Please enter your password');
    return false;
  }

  var custID = document.getElementById('idtb').value;
  if (Number.isNaN(parseInt(custID))) {
    alert("Customer ID needs to be numeric");
    return false;
  }
  
  if (parseInt(custID) < 3000) {
    alert("ID must be above 3000");
    return false;
  }
  
  if (parseInt(custID) > 3999) {
    alert("ID must be below 3999");
    return false;
  }
}
<!DOCTYPE html>
<html>
<body>
<form  action="#" onsubmit="return validatefunctions()" method="post">

  Customer ID: <input type="text" name="idtb" id="idtb"><br /><br />

  Password: <input type="text" name="pwtb" id="pwtb"><br /><br />

  <input type="submit" value="Submit">

</form>
</body>
</html>

Upvotes: 5

Mamun
Mamun

Reputation: 68933

textbox needs to be a number and also a number between 3000 and 3999 (That one doesn't work)

Why don't use input type number specifying the min and max attribute:

<form>
  <input type="number" name="quantity" min="3000" max="3999" value="3000">
  <input type="submit">
</form>

Upvotes: 0

Related Questions