Data validation for donuts

The JavaScript we wrote in the previous post is really basic. Let's improve it a bit adding some data validation.

We rewrite the placeOrder() function, to check any required field. So, name should not be empty, pickup should be a number, and the sum of the requested donuts should be greater than zero.

If we detect some non numeric data in a field that is expected to be numeric, we reset it to empty string:

function placeOrder(form) {

if(document.getElementById("name").value == "") {
alert("Your name is mandatory!");

var pickup = document.getElementById("pickup");
if(pickup.value == "" || isNaN(pickup.value)) {
alert("Please, specify the pickup time");
pickup.value = "";

var cDonuts = parseInt(document.getElementById("cdonuts").value);
if(isNaN(cDonuts)) {
cDonuts = 0;
document.getElementById("cdonuts").value = "";
var gDonuts = parseInt(document.getElementById("gdonuts").value);
if(isNaN(gDonuts)) {
gDonuts = 0;
document.getElementById("gdonuts").value = "";
if(cDonuts + gDonuts == 0) {
alert("Please, order at least one donut!");

// Submit the order to the server
alert("Not implemented yet!");

Post written while reading chapter two of Head First JavaScript, a good book if you know nothing about JavaScript and not much about programming. A bit too slow otherwise.

No comments:

Post a Comment