My javascript regex code does not work for mobile view - javascript

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:
jQuery(function($){
var accepted = "";
$( '.wpf-char-restrict' ).on( 'input', function() {
var regex = /^[a-z0-9 ]*$/i;
if (!regex.test($(this).val())) {
alert ( "Please fill out the form in English. Thank you!" );
$(this).val(accepted);
} else {
accepted = $(this).val();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="wpf-char-restrict">
NB: You may want to allow for some punctuation in the input (like comma, point, ...etc).

Related

How to show native validation error for specific input on change event?

I have a classic HTML5 form. I would like using jquery/javscript to show the browser native error tooltip when the user change a specific input value. I would like to avoid the user try to submit the form to see all errors.
For that, I tried with the functions checkValidity() and reportValidity() but it works only if I add alert('test'); in my condition...so weird
JS script
myInputJqueryObject.on('change', function() {
if ( !this.checkValidity() ) {
this.setCustomValidity( 'Custom error !!!' );
var $form = $('#my-form');
if( $form[0].checkValidity() === false) {
$form[0].reportValidity();
//alert('test'); <-- works only if I active this line code
return true;
}
}
});
You do not need to check the form validity when you know that the input is invalid. You can omit if( $form[0].checkValidity() === false). Also you can reportValidity on the input itself.
And setCustomValidity takes some time to be applied to the input field. So you have to wrap reportValidity into setTimeout:
$('input').on('change', function() {
var self = this;
if (!self.checkValidity()) {
self.setCustomValidity('Custom error !!!');
setTimeout(function() {
self.reportValidity();
self.setCustomValidity('');
}, 1);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="my-form"><input value="del me" required></form>
Based on 'Kosh Very' answer, I found the solution. It sounds good without bugs.
JS Script :
$('input').on('focusout', function() {
var self = this;
var validity = self.checkValidity();
if( !validity ){
if( self.validity.patternMismatch ){ //<-- Optionnal : Condition to keep others native message errors except Pattern.
self.setCustomValidity( 'Custom Error about pattern!!!' );
}
setTimeout(function() {
self.reportValidity();
self.setCustomValidity( '' ); //<-- Important to reinit
}, 1);
}
});

Mozilla browser is treating backspace as special character

problem
i was implementing user cannot enter special character in textbox.
script is working on ie, safari, chrome but mozilla treating as special character.
what i need
i need backspace so that user can edit textbox values.
html code
<input type="text" id="school" name="school"/>
js code
$("#school").bind('keypress', function (event) {
var regex = new RegExp("^[a-zA-Z0-9]+$");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
console.log(key);console.log(flag);
if (!regex.test(key) && flag=="false") {
console.log("if");
//jQuery("#errmsg").html(localStorage.getItem("datas")).show();
event.preventDefault();
return false;
}
else
{
console.log("else");
}
//alert(data);
});
js fiddle link : http://jsfiddle.net/HGJb3/295/
any help is most appericiated.
i came up with solution : http://jsfiddle.net/HGJb3/297/ now it works

Send tweet using 'enter' key (Greasemonkey)

I'm attempting to create a Greasemonkey script that can submit a tweet when a user hits the 'enter' key. I've gotten this to work fine on a simple HTML page (with the help of a few excellent tips on this site). However, when I try to use the code on my twitter page, the alert only fires if a tweet is not currently being authored.
document.onkeyup = function(event){
var keyCode;
if (window.event) // IE/Safari/Chrome/Firefox(?)
{
keyCode = event.keyCode;
}
else if (event.which) // Netscape/Firefox/Opera
{
keyCode = event.which;
}
if (keyCode == 13){
alert("Enter pressed");
}
}
My next thought was to test for a more specific keypress event. So I tried testing for a key event within the new tweet textarea:
document.getElementsByClassName("twitter-anywhere-tweet-box-editor")[0].onkeyup = function(event)
...but this event never seems to fire. I also tried grabbing the element by tag:
document.getElementsByTagName("textarea")[0].onkeyup = function(event)
...but not dice there either. I wonder if this has to do with the fact that the new tweet window is not loaded from the get-go at window.onload(). Thoughts?
I got it thanks to this post. I've also posted the full Greasemonkey script here.
setInterval (function() { checkForTweetbox (); }, 500);
function checkForTweetbox () {
var tweetbox = document.querySelector ('div.tweet-box textarea'); //check for new tweet window
if (tweetbox) {
if (! tweetbox.weHaveProcessed) {
tweetbox.weHaveProcessed = true;
// alert ('New tweet-box found!');
}
}
tweetbox.onkeydown = function(event){
if(event.keyCode == 13){ //13 = Enter keycode
document.querySelector ('a.primary-btn').click(); //there must be at least one character in the textarea
}
}
}

Prevent form submission with enter key

I just wrote this nifty little function which works on the form itself...
$("#form").keypress(function(e) {
if (e.which == 13) {
var tagName = e.target.tagName.toLowerCase();
if (tagName !== "textarea") {
return false;
}
}
});
In my logic I want to accept carriage returns during the input of a textarea. Also, it would be an added bonus to replace the enter key behavior of input fields with behavior to tab to the next input field (as if the tab key was pressed). Does anyone know of a way to use the event propagation model to correctly fire the enter key on the appropriate element, but prevent form submitting on its press?
You can mimic the tab key press instead of enter on the inputs like this:
//Press Enter in INPUT moves cursor to next INPUT
$('#form').find('.input').keypress(function(e){
if ( e.which == 13 ) // Enter key = keycode 13
{
$(this).next().focus(); //Use whatever selector necessary to focus the 'next' input
return false;
}
});
You will obviously need to figure out what selector(s) are necessary to focus on the next input when Enter is pressed.
Note that single input forms always get submitted when the enter key is pressed. The only way to prevent this from happening is this:
<form action="/search.php" method="get">
<input type="text" name="keyword" />
<input type="text" style="display: none;" />
</form>
Here is a modified version of my function. It does the following:
Prevents the enter key from working
on any element of the form other
than the textarea, button, submit.
The enter key now acts like a tab.
preventDefault(), stopPropagation() being invoked on the element is fine, but invoked on the form seems to stop the event from ever getting to the element.
So my workaround is to check the element type, if the type is not a textarea (enters permitted), or button/submit (enter = click) then we just tab to the next thing.
Invoking .next() on the element is not useful because the other elements might not be simple siblings, however since DOM pretty much garantees order when selecting so all is well.
function preventEnterSubmit(e) {
if (e.which == 13) {
var $targ = $(e.target);
if (!$targ.is("textarea") && !$targ.is(":button,:submit")) {
var focusNext = false;
$(this).find(":input:visible:not([disabled],[readonly]), a").each(function(){
if (this === e.target) {
focusNext = true;
}
else if (focusNext){
$(this).focus();
return false;
}
});
return false;
}
}
}
From a usability point of view, changing the enter behaviour to mimic a tab is a very bad idea. Users are used to using the enter key to submit a form. That's how the internet works. You should not break this.
The post Enter Key as the Default Button describes how to set the default behaviour for enter key press. However, sometimes, you need to disable form submission on Enter Key press. If you want to prevent it completely, you need to use OnKeyPress handler on tag of your page.
<body OnKeyPress="return disableKeyPress(event)">
The javascript code should be:
<script language="JavaScript">
function disableEnterKey(e)
{
var key;
if(window.event)
key = window.event.keyCode; //IE
else
key = e.which; //firefox
return (key != 13);
}
</script>
If you want to disable form submission when enter key is pressed in an input field, you must use the function above on the OnKeyPress handler of the input field as follows:
<input type="text" name="txtInput" onKeyPress="return disableEnterKey(event)">
Source: http://www.bloggingdeveloper.com/post/Disable-Form-Submit-on-Enter-Key-Press.aspx
Set trigger for both the form and the inputs, but when the input events are triggered, stop the propagation to the form by calling the stopPropagation method.
By the way, IMHO, it's not a great thing to change default behaviors to anything any average user is used to - that's what make them angry when using your system. But if you insist, then the stopPropagation method is the way to go.
In my case i wanted to prevent it only in a dinamically created field, and activate some other button, so it was a little bit diferent.
$(document).on( 'keypress', '.input_class', function (e) {
if (e.charCode==13) {
$(this).parent('.container').children('.button_class').trigger('click');
return false;
}
});
In this case it will catch the enter key on all input's with that class, and will trigger the button next to them, and also prevent the primary form to be submited.
Note that the input and the button have to be in the same container.
The previous solutions weren't working for me, but I did find a solution.
This waits for any keypress, test which match 13, and returns false if so.
in the <HEAD>
function stopRKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.which == 13) && (node.type == "text")) {
return false;
}
}
document.onkeypress = stopRKey;
I prefer the solution of #Dmitriy Likhten, yet:
it only worked when I changed the code a bit:
[...] else
{
if (focusNext){
$(this).focus();
return false; } //
}
Otherwise the script didn't work.
Using Firefox 48.0.2
I modified Dmitriy Likhten's answer a bit, works good. Included how to reference the function to the event. note that you don't include () or it will execute. We're just passing a reference.
$(document).ready(function () {
$("#item-form").keypress(preventEnterSubmit);
});
function preventEnterSubmit(e) {
if (e.which == 13) {
var $targ = $(e.target);
if (!$targ.is("textarea") && !$targ.is(":button,:submit")) {
var focusNext = false;
$(this).find(":input:visible:not([disabled],[readonly]), a").each(function () {
if (this === e.target) {
focusNext = true;
} else {
if (focusNext) {
$(this).focus();
return false;
}
}
});
return false;
}
}
}

How to REALLY limit the available character for an input field using jQuery?

I just started adding JS-validation to a signup form and I want the username input field in a Twitter-style (using jQuery). That means that the input is limited to certain characters and other characters do not even appear.
So far, I've got this:
jQuery(document).ready(function() {
jQuery('input#user_login').keyup(function() {
jQuery(this).val( jQuery(this).val().replace(/[^a-z0-9\_]+/i, '') );
});
});
This solution works, but the problem is that the illegal character appears as long as the user hasn't released the key (please excuse my terrible English!) and the keyup event isn't triggered. The character flickers in the input field for a second and then disappears.
The ideal solution would be the way Twitter does it: The character doesn't even show up once.
How can I do that? I guess I'll have to intercept the input in some way.
If you want to limit the characters the user may type rather than the particular keys that will be handled, you have to use keypress, as that's the only event that reports character information rather than key codes. Here is a solution that limits characters to just A-Z letters in all mainstream browsers (without using jQuery):
<input type="text" id="alpha">
<script type="text/javascript">
function alphaFilterKeypress(evt) {
evt = evt || window.event;
var charCode = evt.keyCode || evt.which;
var charStr = String.fromCharCode(charCode);
return /[a-z]/i.test(charStr);
}
window.onload = function() {
var input = document.getElementById("alpha");
input.onkeypress = alphaFilterKeypress;
};
</script>
Try using keydown instead of keyup
jQuery('input#user_login').keydown(function() {
Aside: You selector is slower than it needs to be. ID is unique, and fastest, so
jQuery('#user_login').keydown(function() {
Should suffice
You might want to consider capturing the keycode iself, before assigning it to the val
if (event.keyCode == ...)
Also, are you considering the alt, ctls, and shift keys?
if (event.shiftKey) {
if (event.ctrlKey) {
if (event.altKey) {
Thanks #TimDown that solved the issue! I modified your code a little so it accepts backspace and arrows for editing (I post a reply to use code formatting).
Thank you very much.
function alphaFilterKeypress(evt) {
evt = evt || window.event;
// START CHANGE: Allow backspace and arrows
if(/^(8|37|39)$/i.test(evt.keyCode)) { return; }
// END CHANGE
var charCode = evt.keyCode || evt.which;
var charStr = String.fromCharCode(charCode);
// I also changed the regex a little to accept alphanumeric characters + '_'
return /[a-z0-9_]/i.test(charStr);
}
window.onload = function() {
var input = document.getElementById("user_login");
input.onkeypress = alphaFilterKeypress;
};
You can use the maxlength property in inputs and passwords: info (that's actually the way Twitter does it).

Categories

Resources