Forms that allow input must be validated, data element by data element. The input forms I’ve created have data elements whose validation seems to fall into categories that will be repeated across a number of forms.
First, every form’s entry spaces must be checked to see if they are empty or if they are null (not the same thing). They must also be checked to ensure they conform to data type for the element (text, date, numerics, etc). In some cases elements are constrained as to value which must be checked (gender “M” or “F”, name suffix against list, etc). Thus, data validation can be put into 3 categories (in my case): empty/null tests, data type tests, value tests.
JavaScript is the tool most recommended in my searches. Validation is done in the frontend (client) not in the backend (server). From what I’ve learned about JavaScript (so far) functions are created to be used repetitively as is the case for data validation of the sorts mentioned above.
I’ve done a bit of searching and reading, but haven’t found examples of using functions to perform data validation; however I think that would be the proper approach.
Example:
Given a screen form with the variables name (char(20)), birthdate (date), gender (M/F) and age(tinyint), how would one proceed? I’ve looked for examples without finding one.
From my very limited understanding, thedocument. getElementById
method could be used for each data element:
document.getElementById(name)
document.getElementById(birthDate)
document.getElementById(gender)
document.getElementById(age)
I get confused trying to write functions for validating the contents of those methods.
Here’s how I would start (based on articles I read):
<body>
<p>id="name"</p>
</body>
<script>
function validateName() {
let x = "name"
if (x == "") {
alert("Name is required");
return false;
}
document.getElementById(name)
</script>
As I understand the code, the method document.getElementById(name)
takes the value entered in the name blank coded in the body of the HTML document that has id="name"
coded into a form. The value of the named data element is passed to the JavaScript function where its value is tested.
I probably do not understand the process. I probably have syntax and logic errors. I want to know if I do, but there is another issue. Because the method document.getElementById
is specific to the data element ‘name’ , I don’ t see how the function can be used with other data elements - birthdate, gender, age - unless it is coded for each of those data elements. If that’s the case, why use a function? What don’t I understand?
I would appreciate someone taking the time to point out my errors in understanding and any suggestions for articles to read.