How to protect HTML form from blank submission
First you can use the required
attribute on mandatory fields for client-side:
<input type="text" name="mandatory_field" required>
But you will need to verify server-side in case the user modified the form. You can use empty()
on any variable ($_POST
or $_GET
):
if (empty($_POST['mandatory_field'])) {
// print error message or redirect to form page
}
You can use isset()
to verify if a field is submitted. Your validation could be:
if (!isset($_POST['mandatory_field']) || empty($_POST['mandatory_field'])) {
// print error message or redirect to form page
}
Other cases:
If all fields are mandatory you could check with in_array()
:
if (in_array(false, $_POST)) {
// print error message or redirect to form page
}
If doing various data validation here is what I use to do with forms:
$errors = [
'empty field' => empty($_POST['field']),
'another error message' => $another_condition
];
if (in_array(true, $errors)) {
$error_message = array_search(true, $errors);
// print or redirect, and you can tell the user what is wrong
}
How to prevent submitting the HTML form's input field value if it empty
This can only be done through JavaScript, as far as I know, so if you rely on this functionality you need to restructure. The idea, anyway, is to remove the name
attribute from inputs you don't want included:
jQuery:
$('#my-form-id').submit(function () {
$(this)
.find('input[name]')
.filter(function () {
return !this.value;
})
.prop('name', '');
});
No jQuery:
var myForm = document.getElementById('my-form-id');
myForm.addEventListener('submit', function () {
var allInputs = myForm.getElementsByTagName('input');
for (var i = 0; i < allInputs.length; i++) {
var input = allInputs[i];
if (input.name && !input.value) {
input.name = '';
}
}
});
You might also want to reset the form afterwards, if you use a listener and cancel.
Stop an input field in a form from being submitted
You could insert input fields without "name" attribute:
<input type="text" id="in-between" />
Or you could simply remove them once the form is submitted (in jQuery
):
$("form").submit(function() {
$(this).children('#in-between').remove();
});
PHP Forms Submission with blank answers removed - Stop body message from submitting if field is blank
You could make this a lot easier to maintain with a slight rework of your form field names. For example, this line in your script:
$body_message .= 'Reason for Leaving: '.$field_cur_reason_leaving."\r\n";
If you change this form field name to $reason_for_leaving
in your HTML--and do the same for the other fields--you could process your form and generate your email message like this:
$body_message = ''; // initialize email body
foreach ( $_POST as $key => $value ) {
if ($key == 'somethingspecial') {
// special parsing for this field
} else {
// some basic sanitization
$_POST[$key] = trim(stripcslashes(strip_tags( $value )));
if ($_POST[$key] != '') {
// If field isn't blank, make the form field name
// look nice and add the value for the form field
$body_message .= ucwords(str_ireplace( '_', ' ', $key )) .': '. $value . "\r\n";
}
}
}
Obviously, you'll need to do a little more work for special form fields (like your checkboxes), but this should greatly simplify your code (and your life).
Is it a good practice to use an empty URL for a HTML form's action attribute? (action="")
The best thing you can do is leave out the action attribute altogether. If you leave it out, the form will be submitted to the document's address, i.e. the same page.
It is also possible to leave it empty, and any browser implementing HTML's form submission algorithm will treat it as equivalent to the document's address, which it does mainly because that's how browsers currently work:
8.
Let action be the submitter element's action.
9.
If action is the empty string, let action be the document's address.Note: This step is a willful violation of RFC 3986, which would require base URL processing here. This violation is motivated by a desire for compatibility with legacy content. [RFC3986]
This definitely works in all current browsers, but may not work as expected in some older browsers ("browsers do weird things with an empty action="" attribute"), which is why the spec strongly discourages authors from leaving it empty:
The
action
andformaction
content attributes, if specified, must have a value that is a valid non-empty URL potentially surrounded by spaces.
Prevent html input type=number from ever being empty
HTML5 validation rules will only help when the form is submitted. If you want to prevent the input from being empty you'll need to use some JS.
The following (not "ugly JS hack") will work for all number
inputs on a page and insert a value of 0
if the user tries to leave the input empty.
const numInputs = document.querySelectorAll('input[type=number]')
numInputs.forEach(function(input) { input.addEventListener('change', function(e) { if (e.target.value == '') { e.target.value = 0 } })})
<input type="number" required value="0" />
<input type="number" required value="0" />
Related Topics
Angular - Displaying Object Within Object in Json
Accessing Ejs Variable in JavaScript Logic
Javascript on Click Event for Multiple Buttons With Same Class
How to Find Previous or Next Element from Array in JavaScript
Javascript Regex - No White Space At Beginning + Allow Space in the Middle
Pass Parameter from Input to Onclick Method
Input Field Value Should Not Be Greater Than Other Field Value
How to Change Text Value Upon Button Press in React Native
Split a String Only the At the First N Occurrences of a Delimiter
Creating a Leaderboard in Html/Js
How to Read a Properties File in JavaScript from Project Directory
How to Change Data Due to Selected Value in Select Vue
Close Window Automatically After Printing Dialog Closes
How to Share and Edit Global Variables Between Two JavaScript Node Runs
Passing Variable from One Js to Another Js File in Nodejs
Filter Json Object Array on Multiple Values or Arguments JavaScript
How to Remove Single Uploaded File from Jquery in Multiple File Upload