help with if statement - min of 3 characters
Since there is no minlength="" for input, how can I make an if statement that does the following:
If the user has not input more than 3 charact开发者_如何学Pythoners it will not be saved in a database.
Here is the input:
QTY<input title="QUANTITY PER ITEM" size="1" name="inputQTY" value="**(minimun of 3 characters)**"/>
any ideas??
Note: it doesn't matter if there's a min value restriction on the input field or not; a user can still spoof the form to contain whatever value he or she wants. Thus, you need to validate on the server side.
Let's say you're using PHP as your server side language.
$inputQTY = $_POST['inputQTY'];
if (strlen($inputQTY) < 3) {
// DO NOT INSERT INTO DB
}
else {
// insert after further scrubbing input
}
Read this: What's the best method for sanitizing user input with PHP?
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
精彩评论