Form validation is the process of checking if the form fields are filled in correct formats if they are processes. In your question, the correct format is "more than 3 characters". Of course, if statements are involved during form validations. In the client-side, you use JavaScript code to validate form fields.
Here is how it works: A form has an onsubmit
event handler, when the user clicks Submit, or presses Enter, onsubmit
will be triggered. onsubmit
is where you put the form validation code.
<script>
function onsubmit() {
if (document.forms.mainForm.inputQTY.value.length < 3) {
alert("ERROR: Must be more than 3 characters");
return false; // stops the form submission
}
return true;
}
</script>
And here is how you add the onsubmit handler
...
The onsubmit
function can return a value: true to let the form to be submitted, or false to stop the submission.
What is document.forms.mainForm.inputQTY.value.length? document.forms.mainForm
references to the form name
d mainForm
, while .inputQTY
finds the inputQTY
field.
You can use document.getElementsByTagName
to manually find these elements, but it is [time and space]-consuming to write that type of code.
Because some users have JavaScript disabled, or crackers intentionally disable JS to bypass validation, you must validate server-side.
Server-side code will be something like this:
if (strlen($_GET['inputQTY']) < 3) {
echo "ERROR: Must be more than 3 characters";
} else {
// submit data
}
NOTE: code written from head, not tested