How to restrict web form submissions to selected countries using a script field
When handling web forms, spam replies are inevitable. To address this, we have implemented a hidden, non-intrusive CAPTCHA system to filter out bot submissions.
However, another common challenge is the submissions from users in countries where your services may not apply. This guide will show you how to restrict your form submissions to only specific countries using a simple script.
Step-by-Step Implementation
In this example, we’ll use a script field to implement country-based restrictions in your web form.
The script will use the ipapi.co API to identify the user's country based on their IP address and prevent form submission if the user is from a restricted region. They offer a generous free tier, but you’re free to choose any service that best fits your needs.
You can easily customize the following:
- Allowed Countries: Specify the countries you want to allow.
- Error Message: Customize the error message and styling (e.g., color).
- First Input Field: Adjust the script to monitor the first field in your form. In the example it is "title" change it to your first field's id.
Here’s the Code
- Create a script field in your form
- Add it to the webform
- Have this code in the field
return """
<div id="message" style="margin-top: 10px;"></div>
<script>
var scriptField = $('.formrow[data-id="script"]');
scriptField.hide();
$('.formrow[data-id="script"] div.label').hide();
// Selecting the first input field
var firstInputFieldName = "name";
var titleInput = document.querySelector(`.formrow[data-id="${firstInputFieldName}"] .value input[name="${firstInputFieldName}"]`);
// Adding event listener to the title input field for 'change' event
titleInput.addEventListener('change', async function () {
try {
// List of allowed countries.
var allowedCountries = ["United States", "Canada"];
// Fetch user's IP info from an external service
var response = await fetch('https://ipapi.co/json/');
var data = await response.json();
var userCountry = data.country_name;
// Check if user's country is in the allowed list
if (!allowedCountries.includes(userCountry)) {
var captchaInput = document.querySelector('.formrow[data-id="captcha_code"] .value input[name="captcha_code"]');
// Clear the captcha field
captchaInput.value = '';
scriptField.show();
var messageDiv = document.getElementById('message');
messageDiv.style.color = 'red';
messageDiv.textContent = 'Invalid submission: your country is restricted from completing this form.';
$('button.primary').hide();
}
} catch (error) {
// console.error("Error fetching user data:", error);
}
});
</script>
"""