Still fairly new to JavaScript trying to validate some text field input, I've been trying to do it step by step but there's a lot going on and I keep contradicting myself. I've explained the required validation below.
var a = document.getElementById("val1").value;
var b = document.getElementById("val2").value;
val1 and val2 refer to two text input fields, a and b both have to be positive integers, but only one input field has to be filled, in that case the other variable should be given the value 0, then variable a should be the smaller of the two values and b the largers, in order for me to run the following loop.
for (var i = a; i < (Number(b) + Number(1)); i++) {
tableRow = resultsRows.appendChild(document.createElement("tr"));
if(i%2==0) {
tableRow.setAttribute("class", "even");
}
else {
tableRow.setAttribute("class", "odd");
}
var tableData = tableRow.appendChild(document.createElement("td"));
tableData.appendChild(document.createTextNode(i));
tableData = tableRow.appendChild(document.createElement("td"));
tableData.appendChild(document.createTextNode(converter(i)));
}
Function I was trying to write to validate this. Not sure how to accept blank input with this...
function validateInput(x) {
if (isNaN(x) || x < 0) {
alert("Input incorrect; fields must be blank or contain positive integers");
return false;
}
else { return true
}
}
Please try the attached code snippet. It is designed to incorporate the following assumptions:
function customValidation(){ var a = document.getElementById("val1").value; var b = document.getElementById("val2").value; if((a == "" && b == "") || (a > "" && !isNumber(a)) || (b > "" && !isNumber(b)) || (a < 0 || b < 0) || (a == 0 && b == 0) || (a > 0 && b > 0)){ alert("Input incorrect; " + "only one of the fields must contain a value " + "and that should be a positive number"); return false; } if(a > 0){ n = a; } else{ n = b; } for(i=0; i < (Number(n) + Number(1)); i++){ alert("Executing: "+i); // // } } //----------------------------------------------------- function isNumber(n) { return !isNaN(parseFloat(n)) && isFinite(n); } //-----------------------------------------------------
Val1: <input id="val1" type="text"><br> Val2: <input id="val2" type="text"><br> <input type="button" value="Test" onClick="customValidation()">
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.