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
Related
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).
I have this script that only allow numbers to be typed in and everything works great but I want to be able to paste only numbers if the user decides to use paste in an input.
The paste i'm referring to is mouse paste and keyboard paste. Paste in general. I tried to figure this out but I can not seem to find a way to do this.
Here is my code.
//Prevent non numbers from keypress
document.querySelector('#numbers-only').addEventListener('keypress',preventNonNumbersInInput);
function preventNonNumbersInInput(event){
var characters = String.fromCharCode(event.which);
if(!(/[0-9]/.test(characters))){
event.preventDefault();
}
}
//Prevent non numbers from being pasted only numbers can be pasted
document.querySelector('#numbers-only').addEventListener('paste',pasteTest);
function pasteTest(){
//???
}
<input type="text" id='numbers-only'>
Here you go.
You can create a list of invalid chars to prevent on keydown i.e. paste.
Below is working code:
var input = document.getElementById("numbers-only");
var invalidChars = [
"-",
"+",
"e",
"."
];
input.addEventListener("input", function() {
this.value = this.value.replace(/[e\+\-]/gi, "");
});
input.addEventListener("keydown", function(e) {
if (invalidChars.includes(e.key) || e.which === 38 || e.which === 40) {
e.preventDefault();
}
});
input[type="number"]::-webkit-outer-spin-button,
input[type="number"]::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
<input type="number" id="numbers-only" />
Since it is an input you can easly change che input type to number.
The web browser will then take care of allowing only numbers.
<input type="number" id='phone-number'>
I am creating a webapp for android device using html5,javascript and css3. I have a screen which has a textarea. User can enter his comments in the textarea. On clicking the android enter/return key of keyboard, the cursor should move to next line in the textarea.
Any help on this feature ?
I tried many ways. like
$('#reply').bind('keyup', function(e) {
var data = $('#reply').val();
logger.debug("data = " + data);
$('#reply').text(data.replace(/\n/g,"<br />"));
});
#reply is the id of my textarea.
No luck....
Return key can be checked using this key code 13 and just append newline character to force user to write on newline:
$("#reply").on('keydown', function(e) {
var code = e.keyCode || e.which;
if(code == 13) { //Enter keycode
event.preventDefault();
var s = $(this).val();
$(this).val(s+"\n");
}
});
There's a TextBox that I wanna allow users to just enter numbers & not any alphabetical characters.
So how could I ignore those chars entered by end user via JavaScript or jQuery?
Notice I don't wanna replace user's entered value by empty string; Instead wanna ignore case if there is any way for it.
Try that code:
$("#id").keypress(function (e) {
//if the letter is not digit then display error and don't type anything
if ( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)) {
return false;
}
});
reference http://roshanbh.com.np/2008/04/textbox-accept-only-numbers-digits.html
You want to attach a handler to the textbox's keypress event. In here check the event.which property to find out what key is pressed, and if it's not a number (between keycodes 48 and 57) return false, which will cancel the default behaviour of typing in the textbox.
$("input").keypress(function (e) {
if (e.which < 48 || e.which > 57)
return false;
});
I would not recommend intercepting keystrokes, allow the user to type whatever he/she wants, and validate on user action (submit/select etc).
Look at this jQuery plugin for instance: http://bassistance.de/jquery-plugins/jquery-plugin-validation/
you said you didn't want to include alphabetical then you said you just want to ignore case? what do you need to do?
You can ignore lower case in JS by using string.toLowerCase()
For numeric-only I use this jQuery extension/plug in
http://www.texotela.co.uk/code/jquery/numeric/
In above options we can prevent the user from keyboard, but what if the user paste something, it will not restrict user to not paste any special character.
For example we are restricting it from keyboard with proper error msg
<script type="text/javascript">
$(function () {
$("#package").keypress(function (e) {
var keyCode = e.keyCode || e.which;
$("#lblError").html("");
//Regex for Valid Characters i.e. Alphabets and Numbers.
var regex = /^[A-Za-z0-9]+$/;
//Validate TextBox value against the Regex.
var isValid = regex.test(String.fromCharCode(keyCode));
if (!isValid) {
$("#lblError").html("Only Alphabets and Numbers allowed.");
}
else
{
$("#lblError").html("");
}
return isValid;
});
});
</script>
Now let's prevent it from pasting special character.
$('#package').bind("paste",function(){
var data= $('#package').val() ;
var removedNotAllowed = data.replace(/[^ws]/gi, '');
$( '#package' ).val(removedNotAllowed);
$("#lblError").html("Only Alphabets and Numbers allowed.");
});
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).