Home Javascript validation for a html form not working
Reply: 1

Javascript validation for a html form not working

oliver thomas
1#
oliver thomas Published in 2017-12-07 21:34:59Z

----------SOLVED------------

I'm trying to do a validation for a form so that if any of the fields are left blank, there is an alert and the form wont go through, but it is still inputting null values into the database

function validateAdd() {
  var a = document.add_product.product_id.value;
  var b = document.add_product.brand.value;
  var c = document.add_product.model.value;
  var h = document.add_product.description.value;
  var d = document.add_product.cam_mpx.value;
  var e = document.add_product.storage.value;
  var f = document.add_product.more_storage.value;
  var g = document.add_product.price.value;
  if (a == "" || b == "" || c == "" || d == "" || e == "" || f = "" || g == "" || h == "" ||
    a == null || b == null || c == null || d == null || e == null || f = null || g == null || h == null) {
    alert("All fields must be filled in");
    return false;
  }
}
<form name="add_product" action="index.php" method="post" onsubmit="return validateAdd()">
  <label>Product ID:</label><br>
  <input type="text" name="product_id"><br>
  <label>Brand:</label><br>
  <input type="text" name="brand"><br>
  <label>Model:</label><br>
  <input type="text" name="model"><br>
  <label>Description:</label><br>
  <input type="text" name="description"><br>
  <label>Camera Megapixel:</label><br>
  <input type="text" name="cam_mpx"><br>
  <label>Storage:</label><br>
  <input type="text" name="storage"><br>
  <label>Expandable Storage?:</label><br>
  <input type="text" name="more_storage"><br>
  <label>Price:</label><br>
  <input type="text" name="price"><br>
  <button class="button" type="submit" name="save" onclick="return confirm('Are you sure you want to add this to the system?')">Add</button><br>
  <p></p>
</form>

ericw31415
2#
ericw31415 Reply to 2017-12-07 21:50:47Z

Well, on these two lines, you do f = "" and f = null instead of f == "" and f == null:

if (a == "" || b == "" || c == "" || d == "" || e == "" || f = "" || g == "" || h == ""
        || a == null || b == null || c == null || d == null || e == null || f = null || g == null || h == null) {

You would have noticed to look there from Uncaught ReferenceError: Invalid left-hand side in assignment being errored to the console.

I would suggest that you shorten that down to

if (!(a && b && c && d && e && f && g && h)) {

because it's way easier to debug.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.370567 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO