HTML and CSS Reference
In-Depth Information
Plan
Ahead
Validating form input.
The validations and calculations in this project require two separate user-defined functions.
In order to calculate the monthly payment, the values entered into the text fields must be
valid numbers. A user-defined function called validSalesAmt() performs the following steps
to validate the text field entries and calculate the loanAmt:
Convert the text field value to a numeric value using the parseInt() or parseFloat() function
Use the isNaN (is Not a Number) function to verify the value is numeric and then verify
the value is greater than zero
Use an if statement to test if the value is not a number or is zero or less, display an
error message, clear the text field, and position the insertion point in that text field
Subtract the down payment amount from the sales amount to calculate the loan
amount
To call the validSalesAmt() validation function, an onBlur event handler is added to the form.
Once the loan amount is calculated, the user must enter the loan interest rate and the
number of years to pay the loan off. The valid number of years are displayed on the form
in a <select> list, but the validation must still verify a number was selected. A user-defined
function called CalcLoanAmt() follows these steps to validate the text field and <select> list
entries and calculate the monthly payment:
For the loan rate, convert the loan rate text field value to a numeric value using the
parseInt() or parseFloat() function
If the value is not a number or is zero or less, display an error message, clear the text
field, and position the insertion point in that text field
For the loan years, convert the years text field value to a numeric value using the
parseInt() function
Use the isNaN (is Not a Number) function to verify a valid value was selected from the
drop-down menu
Adding a Loan Calculator
with Validation
Validating Web
Form Data
Web developers use
multiple techniques
to validate Web forms
using JavaScript. Some
developers choose to
validate each item as
it is entered by using a
combination of onchange
event handlers and user-
defined functions. It is
important to validate Web
forms because some Web
databases are sensitive
to invalid data and may
crash, or mathematical
formulas may cease to
function when using
invalid data.
The mortgage loan payment calculator form shown in Figure 10-14 requests user input.
The form, which is named homeLoanForm, has already been created in the HTML
file. JavaScript code must be added to validate the input, calculate the loan amount, and
display the results in the homeLoanForm form. In order for the calculator to work, each
text field must have a valid data entry. You will write two user-defined functions, one
called validSalesAmt() and the other CalcLoanAmt(), to perform these three tasks. Other
JavaScript user-defined functions will calculate the monthly payment and display the
formatted results.
 
Search WWH ::




Custom Search