Introduction
When building forms with Ninja Forms on WordPress, ensuring the quality of collected phone numbers in your Ninja Forms phone field can reduce wasted effort and improve the user experience. One common need is to prevent users from entering phone numbers that start with specific digits, for example numbers that begin with 0
, 1
, or a country or area code like 88
, especially when using a masked phone input. Masked inputs help format numbers visually, for example (123) 456-7890
, but they add complexity when you want to block certain starting sequences. This article walks through a practical JavaScript solution that integrates with Ninja Forms front-end, explains how it works, and offers tips to adapt and maintain it.
Why block specific starting digits?
There are several reasons you might want to stop phone numbers beginning with particular digits:
- Business rules: your service might only accept numbers from given regions or number ranges.
- Validation hygiene: avoid collecting obviously invalid or placeholder numbers like those starting with
0
or000
. - Reduced follow-up effort: filtering invalid numbers early saves time for customer support and sales teams.
Overview of the provided solution
The code shown in the clipboard is a jQuery-based script designed to run in the browser and intercept keyboard and input events for Ninja Forms phone fields. The script:
- Targets masked phone inputs using selectors used in many Ninja Forms setups.
- Blocks single-digit starts such as
0
or1
and multi-digit starts such as88
. - Handles both direct typing and masked formatting quirks such as parentheses and other formatting characters.
- Cleans pasted or programmatically inserted values that start with blocked sequences.
- Tries to position the caret, that is the cursor, in the correct place after modifications to maintain a good user experience.
Code Snippet
/**
* Ninja Forms Phone Starting Digits Blocker
* @author Faisal Ahammad <[email protected])
*/
jQuery(document).ready(function($) {
// Configuration: Add numbers you want to block from starting the phone number
const BLOCKED_STARTING_NUMBERS = ['0', '1', '88'];
function initPhoneValidation() {
let phoneInput = $('.phone-container .phone-wrap input.ninja-forms-field');
if (phoneInput.length > 0) {
phoneInput.each(function() {
const $input = $(this);
$input.off('.phoneValidation');
$input.on('keypress.phoneValidation keydown.phoneValidation', function(e) {
if (BLOCKED_STARTING_NUMBERS.includes(e.key)) {
const value = $(this).val();
const cursorPos = $(this).prop('selectionStart');
const digitsOnly = value.replace(/\D/g, '');
if (value.includes('(') && value.includes(')')) {
if (cursorPos <= 1) {
e.preventDefault();
return false;
}
} else {
if (digitsOnly.length === 0) {
e.preventDefault();
return false;
}
}
}
// Handle multi-digit blocked numbers like '88'
const value = $(this).val();
const digitsOnly = value.replace(/\D/g, '');
const potentialStart = digitsOnly + e.key;
BLOCKED_STARTING_NUMBERS.forEach(blocked => {
if (blocked.length > 1 && potentialStart.startsWith(blocked)) {
e.preventDefault();
return false;
}
});
});
$input.on('input.phoneValidation', function(e) {
const value = $(this).val();
const digitsOnly = value.replace(/\D/g, '');
let shouldClean = false;
let cleanedDigits = digitsOnly;
// Check if starts with any blocked number
BLOCKED_STARTING_NUMBERS.forEach(blocked => {
if (digitsOnly.startsWith(blocked)) {
cleanedDigits = digitsOnly.substring(blocked.length);
shouldClean = true;
}
// Handle masked input format
if (value.startsWith('(' + blocked)) {
const newValue = value.replace('(' + blocked, '(');
$(this).val(newValue);
setTimeout(() => {
this.setSelectionRange(1, 1);
}, 1);
shouldClean = false; // Already handled
}
});
if (shouldClean && cleanedDigits !== digitsOnly) {
$(this).focus().val('');
setTimeout(() => {
$(this).val(cleanedDigits);
$(this).trigger('input');
}, 10);
}
});
$input.on('focus.phoneValidation', function() {
const value = $(this).val();
if (value === '(000) 000-0000' || value.includes('000')) {
setTimeout(() => {
this.setSelectionRange(1, 1);
}, 1);
}
});
});
return true;
}
return false;
}
initPhoneValidation();
setTimeout(initPhoneValidation, 100);
setTimeout(initPhoneValidation, 500);
setTimeout(initPhoneValidation, 1000);
});
Final preview

How to add custom JavaScript code
Key parts of the code explained
1. Block list configuration
The script uses an array to list blocked starts:
const BLOCKED_STARTING_NUMBERS = ['0', '1', '88'];
You can adjust this array to add or remove blocked prefixes.
2. Initialization and selector
The script’s initPhoneValidation function finds phone inputs using a selector such as:
let phoneInput = $('.phone-container .phone-wrap input.ninja-forms-field');
This selector matches many standard Ninja Forms phone-field DOM structures. If your form uses different classes or markup, inspect the DOM and update the selector accordingly.
3. Keypress and keydown interception
The code listens to keypress and keydown events and prevents entry when:
- The typed key matches a blocked single-digit start, and the current number is at its start.
- A typed key leads to a multi-digit blocked prefix, for example typing the second 8 leads the digits to start with 88.
4. Input event handling
The script’s input handler strips non-digit characters and checks whether the resulting digits start with any blocked prefix. If so, it removes the blocked portion and sets the cleaned value while trying to keep the caret in place and re-triggering input events so other masking code stays in sync.
5. Focus behavior
When the field gets focus and has a placeholder-like value, such as (000) 000-0000
, the code positions the caret so the user can start typing immediately.
Integration and deployment steps
1. Add the script to your site
Add the JavaScript in a way that is compatible with Ninja Forms and will not be lost during updates. Options include:
- Use a plugin that allows safe insertion of custom JavaScript into the frontend, for example Code Snippets.
- Include it in a child theme’s JavaScript bundle.
2. Ensure jQuery and masking scripts load first
This script expects the phone masking script, if any, and jQuery to be loaded. Enqueue your script with jQuery as a dependency and with an appropriate priority so it initializes after Ninja Forms has rendered fields.
3. Adjust the selector if necessary
If your Ninja Forms phone field uses a different CSS class, inspect the DOM and update the following code.
$('.phone-container .phone-wrap input.ninja-forms-field');
4. Test across browsers and devices
Because masking and caret placement can behave differently, verify behavior on:
- Desktop browsers such as Chrome, Firefox, Edge, and Safari
- Mobile browsers such as iOS Safari and Android Chrome
- With keyboard and paste inputs
Example modifications and customizations
1. Changing blocked prefixes
To block additional prefixes, update the array:
const BLOCKED_STARTING_NUMBERS = ['0', '1', '7', '88', '999'];
2. Using regular expressions for more complex rules
If you need to block ranges, for example any number starting with digits 0 to 2, use a regular expression in the input handler rather than exact string matching:
const blockedPattern = /^(?:[0-2]|88)/;
Then test with blockedPattern.test(digitsOnly)
.
3. Use custom help text
To improve UX, add a custom Help Text under Field → Display → Help Text
. This lets users easily understand why certain digits cannot be entered.
Common pitfalls and how to avoid them
- Selector mismatch: if you cannot catch the input, confirm the DOM structure and change the selector accordingly.
- Masking conflicts: if another script formats input on input events, race conditions can occur. Ensure your script triggers after the mask or integrate with the mask library’s callbacks if available.
- International numbers: if you accept international numbers with country codes, blocking a specific starting digit might need to occur after stripping country prefixes.
- Paste events: the script handles input events, including paste. However, test paste behavior thoroughly, especially when users paste formatted numbers that include parentheses, spaces, or plus signs.
Frequently Asked Questions (FAQ)
How do I change which prefixes are blocked?
Edit the BLOCKED_STARTING_NUMBERS array near the top of the script. For example, to also block numbers starting with 7
and 999
, use ['0','1','7','999']
.
Will this script stop pasted numbers that start with blocked digits?
Yes. The script listens to the input event and strips blocked prefixes from values, so pasted numbers should be cleaned or prevented.
Do I need server-side validation too?
Absolutely. Client-side validation improves user experience but can be bypassed. Always enforce the same rules on the server before accepting or processing phone numbers.
The script does not seem to affect my Ninja Form phone field. What might be wrong?
The most likely cause is a selector mismatch. Inspect your form’s HTML and update the selector used to locate the input. Also ensure the script runs after the form and its mask plugin are loaded.
Can this script be adapted for international formats?
Yes. You will need to strip or account for country codes and any leading plus signs before testing prefixes. Consider normalizing numbers to digits-only after removing plus and country code before checking.
Could this script remove digits unexpectedly?
If the selector is incorrect or a race condition exists with another masking script, it can lead to unexpected behavior. Test thoroughly and add visible feedback so users understand what happened.
What about users who type quickly or use mobile keyboards?
Mobile keyboards and fast typing can change event timing. The script handles input events which include those cases, but thorough testing on target devices is necessary.
Where should I add the script in WordPress to ensure it is safe from theme updates?
Place it in a child theme or enqueue it via functions.php in a child theme. Alternatively, use a plugin such as Code Snippets to add frontend JavaScript safely.
Is it better to block prefixes or validate allowed prefixes?
In many cases, it is safer to validate allowed patterns rather than only blocking disallowed prefixes, particularly when you accept international numbers. Whitelisting known valid patterns reduces accidental rejection of legitimate numbers.
Conclusion
Blocking certain starting digits in Ninja Forms phone fields helps enforce business rules and keep contact data clean. The jQuery script described provides a practical client-side solution compatible with masked inputs by intercepting keyboard events and cleaning input values. Remember to adapt the selector and blocked prefix list to your needs, test across browsers and devices, and always replicate validation on the server. Combining user-friendly client-side checks with robust server-side enforcement will help preserve data quality without unduly frustrating legitimate users.
Leave a Reply