简体   繁体   中英

having issues with validation in javascript

I am building a travel agency program. I have been having trouble with setting a limit of people who can purchase a trip for example. The number I enter in the text field can only be positive and greater than 0 or a message "disabled" will be displayed as well as an error message. If the number is positive, the message will read "enabled" and I will be able to carry on. It's kind of a stupid question but I'm pretty new with javascript and I would appreciate the help. I will leave the code below.

var enabled = false;

function validation(limit) {

  limit = parseInt($("#limit").val());

  if (!/\d/.test(limit)) {
    $("#enablemessage").show();
    $("#message").show();
    document.getElementById("message").style.color = "red";
    document.getElementById("enablemessage").innerHTML =
      "Disabled";
    document.getElementById("enablemessage").style.color = "red";
    $("#message").html("The value is not a number");
  } else if (limit == null || limit < 1) {
    $("#enablemessage").show();
    $("#message").show();
    document.getElementById("enablemessage").innerHTML =
      "Disabled";
    document.getElementById("enablemessage").style.color = "red";
    $("#message").html("The value must be greater than 1");
  } else if (limit >= 1) {
    enabled = true;
  }
  if (enabled) {
    $("#enablemessage").show();
    $("#message").show();
    document.getElementById("message").style.color = "green";
    document.getElementById("enablemessage").innerHTML = "Enabled";
    document.getElementById("enablemessage").style.color = "blue";
    $("#message").html("The value is correct " + limit);
  } else if (enabled == false) {
    $("#enablemessage").show();
    document.getElementById("enablemessage").innerHTML =
      "Disabled";
    document.getElementById("enablemessage").style.color = "red";
  }

}

The function parseInt returns either a number or the flag NaN . That means that the very first if never returns true. You can change it to eg: if(isNaN(limit)) .

To set a fixed upper limit just test for it eg: if(limit > 8) and do something if the number in limit is greater than 8.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM