Java Reference
In-Depth Information
Let's first look at the
checkUsername()
function. It has been rewritten to use the
try...catch
and
throw
statements for validating the username
<input/>
element, and the majority of this function's
code resides within the
try
block:
try {
if (!userValue) {
throw {
message: "Please enter a user name to check!"
};
}
var parms = {
username: userValue
};
$.getJSON("ch14_formvalidator.php", parms).done(handleResponse);
}
Before you make the Ajax request, you first ensure the user provided a value to the username field. If
userValue
is blank, you
throw
a new object detailing the cause of the exception with its
message
property. This causes
the JavaScript engine to stop executing code in this
try
block and starts executing the
catch
block:
catch (ex) {
alert(ex.message);
}
Here, you simply alert the exception's
message
property, displaying the “
Please enter a user name
to check!
” message to the user.
Naturally, the changes made to the
checkEmail()
function are almost identical to
checkUsername()
:
try {
if (!emailValue) {
throw {
message: "Please enter an email address to check!"
};
}
var parms = {
email: emailValue
};
$.getJSON("ch14_formvalidator.php", parms).done(handleResponse);
} catch (ex) {
alert(ex.message);
}
Once again, the majority of the function code resides within a
try
code block. If the e‐mail field
validation fails, you
throw
an object containing the exception message and display that message in an
alert
box—the result of executing the code in the
catch
block.