I am working on a personal project and am trying to do some error validation on a form using HTML5 and JavaScript.
My HTML code:
<body>
<header>
<h1>BPMeasure</h1>
</header>
<form onsubmit="return false" oninput="o.value = main();">
Track A: <input name="input_a" id="input_a" type="number" min="0.0" max="200.0" value="0"><br/>
Track B: <input name="input_b" id="input_b" type="number" min="0.0" max="200.0" value="0"><br/>
<br />
Output: <output name="o" for="a b"></output>
</form>
</body>
My JavaScript Code:
function calculate(track_a, track_b) {
if(track_a > track_b) {
return ((track_a - track_b) / track_a) * 100;
} else if(track_a < track_b) {
return ((track_a - track_b) / track_b) * 100;
} else {
return 0.0;
}
}
function main() {
var track_a = input_a.valueAsNumber;
var track_b = input_b.valueAsNumber;
var message = isTrackValid(track_a, track_b);
if(message !== "") {
return message;
} else {
return calculate(track_a, track_b);
}
}
Right now, isValid() is a placeholder. I want it so when someone enters an invalid number into track_a or track_b they get an error message in the output (the return message portion). An invalid number is specifically something like 3+, 3++, 3.-4, 5..5, etc.
To figure out if the input was invalid I use this css code:
form input[type=number]:invalid {
background-color: #ff8878;
}
Unfortunately, I have to use this because if someone enters an invalid number (like the examples above), it will always return NaN. This means that if the user hasn't even typed anything we have the value NaN, which means it continually displays an error message. This is why I have the invalid css code above.
My question is, is there a way in JavaScript to detect if the input currently has the attribute invalid, and if so can I return an error message until they either fix the error or clear the input?