I used the following code in WPforms on Wordpress to only allow english characters, numbers and space char in my form. Everything works great until you try it from mobile (the same website and same form, Chrome on Android for example), it just does not work and allows you to fill out any character to the fields.. is there any way to prevent it? I mean to make it work for mobile and don't allow visitors to put special characters from mobile too?
function wpf_dev_char_restrict() {
?>
<script type="text/javascript">
jQuery(function($){
$( '.wpf-char-restrict' ).on( 'keypress', function(e){
var regex = new RegExp('^[a-zA-Z0-9 ]+$');
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
alert ( "Please fill out the form in English. Thank you!" ); // Put any message here
e.preventDefault();
return false;
}
});
//Prevent any copy and paste features to by-pass the restrictions
$( '.wpf-char-restrict' ).bind( 'copy paste', function (e) {
var regex = new RegExp('^[a-zA-Z]+$');
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
alert ( "Pasting feature has been disabled for this field" ); // Put any message here
e.preventDefault();
return false;
}
});
});
</script>
<?php
}
add_action( 'wpforms_wp_footer_end', 'wpf_dev_char_restrict', 10 );
Use the
input
event. This event will fire whatever the input method is: keyboard, mouse drag/drop, context menu, clipboard, other device.This event triggers when the input has already changed, so you'd need to keep track of the value as it was before the latest modification:
NB: You may want to allow for some punctuation in the input (like comma, point, ...etc).