Javascript: return true not working - javascript

I need to prevent a textbox from entering alphabets and any other special characters except dot character. Here is my function:
function key_block(current_element,event){
var str = current_element.val();
//alertify.log(str);
var regex = new RegExp("^[0-9.]+$");
var key = String.fromCharCode(event.charCode ? event.which : event.charCode);
if (regex.test(str)) {
//event.preventDefault();
return true;
} else {
current_element.val('');
return false;
}
}
if(key_block($(this),e)){
//allow typing
}
The code works fine in Chrome Browser. But in Firefox, this is not working fine. I get value "true" for regex.test(str) in firefox. But I don't know why this does not allow me to type the code. Can anyone find the real problem here?

If I understand your question correctly, you're filtering the incoming event's charCode to block unwanted characters. If that's the case, I think you need to test key instead of str:
if (regex.test(key)) {

Related

How to stop numbers from being entered in a contenteditable element

JSFiddle: https://jsfiddle.net/mqfntbws/
I have a contenteditable span in which I want to prevent users from typing special characters or numbers. The problem is, I'm able to prevent special characters but it won't work on numbers. Anyone know what I'm doing wrong?
HTML:
<span required="" contenteditable="" placeholder="First Name" aria-required="true"></span>
JS:
$('span[contenteditable]').on('keypress', function (event) {
var regex = new RegExp("^[A-z]+$");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key) && !((event.keyCode>=46 && event.keyCode<=58) || event.keyCode==8 || event.keyCode==9 || (event.keyCode>=37 && e.keyCode<=40))) {
console.log(">>>");
event.preventDefault();
return false;
}
});
As you appear to be using jQuery, you can make full use of the isNumeric() function within the API.
From the documentation:
The $.isNumeric() method checks whether its argument represents a numeric value. If so, it returns true. Otherwise it returns false. The argument can be of any type.
So using this cleans up your if statement immensely.
if(!regex.test(key) || $.isNumeric(key))
Leaving you with the following:
$('span[contenteditable]').on('keypress', function (event) {
var regex = new RegExp("^[A-z]+$");
var key = String.fromCharCode(event.which);
if (!regex.test(key) || $.isNumeric(key)) {
event.preventDefault();
return false;
}
});
I have forked and updated your original fiddle with a working example: https://jsfiddle.net/GH05T/mqfntbws/6/

Javascript Regex to limit Text Field to only Numbers (Must allow non-printable keys)

I have received PHP/JS code from previous developer and I need to add number validation to a Mobile Number field. I already have the HTML validation in place but I need to add that if someone presses an invalid key, that it doesn't get displayed only to highlight the field later in red because it contains invalid input.
I've seen many regex's used and tried them but they had an either/or effect from what I need which is: If a letter or special character is entered, do not accept and do not display, all other input (digits, keys) is accepted (I need the invalid character not be displayed at all, not displayed and then erased). The regex that is working the most now is this:
function filterNonDigits(evt)
{
var event = evt || window.event;
var keyentered = event.keyCode || event.which;
keyentered = String.fromCharCode(keyentered);
//var regex1 = /[0-9]|\./;
var regex2 = /^[a-zA-Z.,;:|\\\/~!##$%^&*_-{}\[\]()`"'<>?\s]+$/;
if( regex2.test(keyentered) ) {
event.returnValue = false;
if(event.preventDefault) event.preventDefault();
}
When I used the commented regex1 (with the IF condition reversed), naturally it limited input to only digits thus preventing all keys such as Delete, BackSpace, etc. When using regex2, I still can't press Delete or the digits from the numpad.
So my question is, can the above code be modified to accept only digits but also allow keys? Another important point is that I need a method that doesn't use keycodes (8, 24 etc) for those key, in order to make sure all keyboard types can be used.
New Update:
So my solution is as follows: If the "oninput" property exists, I use the solution provided by Ehtesham and if it doesn't, the backup uses the solution provided by Rohan Kumar. So it's something like this:
if (obj.hasOwnProperty('oninput') || ('oninput' in obj))
{
$('#mobileno').on('input', function (event) {
this.value = this.value.replace(/[^0-9]/g, '');
});
}
else
{
$('#mobileno').on('keypress',function(e){
var deleteCode = 8; var backspaceCode = 46;
var key = e.which;
if ((key>=48 && key<=57) || key === deleteCode || key === backspaceCode || (key>=37 && key<=40) || key===0)
{
character = String.fromCharCode(key);
if( character != '.' && character != '%' && character != '&' && character != '(' && character != '\'' )
{
return true;
}
else { return false; }
}
else { return false; }
});
}
Thanks.
The best method here is to use input event which handles all your concerns. It is supported in all modern browsers. With jQuery you can do like following. Handles all cases pasting the value with mouse/keyboard backspace etc.
$('.numeric').on('input', function (event) {
this.value = this.value.replace(/[^0-9]/g, '');
});
See it here
You can check if input event is supported by checking if the input has this property if not you can use onkeyup for older browsers.
if (inputElement.hasOwnProperty('oninput')) {
// bind input
} else {
// bind onkeyup
}
A nice solution is described in a previous post:
jQuery('.numbersOnly').keyup(function () {
this.value = this.value.replace(/[^0-9\.]/g,'');
});
Try it like,
CSS
.error{border:1px solid #F00;}
SCRIPT
$('#key').on('keydown',function(e){
var deleteKeyCode = 8;
var backspaceKeyCode = 46;
if ((e.which>=48 && e.which<=57) ||
(e.which>=96 && e.which<=105) || // for num pad numeric keys
e.which === deleteKeyCode || // for delete key,
e.which === backspaceKeyCode) // for backspace
// you can add code for left,right arrow keys
{
$(this).removeClass('error');
return true;
}
else
{
$(this).addClass('error');
return false;
}
});
Fiddle: http://jsfiddle.net/PueS2/
Instead of checking for the event keyCode, why don't you just check for changes inside the actual input and then filter out non-numbers?
This example uses keyup so that it can read what was actually entered, which means the character is briefly displayed and then removed, but hopefully you get my gist. It might even give the user feedback that the character is not allowed. Either way I think this is the easiest setup, let me know if you need more help fleshing this out.
function filterNonDigits(evt)
{
var event = evt || window.event;
var val = event.target.value;
var filtered = val.replace(/[^0-9]/g, '');
if(filtered !== val) {
event.target.value = filtered;
event.target.className += " error";
}
}
http://jsfiddle.net/mEvSV/1/
(jquery used solely to easily bind the keyup function, you won't need it for your actual script)
/\d/ is equivalent to the above described /[0-9]/. src: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#special-digit
This is a bit more concise...
this.value = this.value.replace(/\D/gm, '');

Restricting Multilanguages for input field

I have got a task to restrict the input field from non English languages.Only English should be enter on the field.
MY textbox is
<input type="text"/>
The function is
$(document).on("keypress", "input[type='text'] function (event) {
return suppressNonEng(event);
});
function suppressNonEng(EventKey) {
var key = EventKey.which || EventKey.keyCode;
if (key > 128) { sefAlert("Only English is allowed"); return false; }
else { return true; }
}
Its worked in the case of Chinese,Greek and some other also.But in the case of Spanish,French, its not working because the same ASCII character is used in the English and French. Is there any solution for this problem?please help
Fiddle
Its pretty simple. You need to match every character entered with a regex that checks whether the character entered is from the English alphabet, or not.
$("#mytextbox").on("keypress", function(event) {
var englishAlphabetAndWhiteSpace = /[A-Za-z ]/g;
var key = String.fromCharCode(event.which);
if (englishAlphabetAndWhiteSpace.test(key)) {
return true;
}
alert ("this is not in English");//put any message here!!!
});
After your comments:
Every key on the keyboard has a keycode. So when you press a key like E, the computer will interpret it as a keycode (69, in this case). It's difficult to make the computer understand the difference between French E or English E.
If you dont want to alert the user, just replace the alert with return false;.
If you need to detect the browser language:
Use this:
var userLang = navigator.language || navigator.userLanguage;
alert ("The language you are using is: " + userLang);
if(userLang!=whatever-you-want){
alert("only whatever-you-want allowed!!!")
}
Check your language
You could use Regex and allow only a-zA-z without any accents or funny letters.

mac-address-validation in javascripts (00:00:00:00:00:00)

Can anyone send javascript code to validate the network mac address (eg. 02:41:6d:22:12:f1) It accepts value from 00:00:00:00:00:00 to ff:ff:ff:ff:ff:ff. On keypress event of textbox, I need to allow characters 0-9, a-f and : (colon). What I have so far is
macPattern = /^([0-9a-fA-F]{2}[:-]){5}[0-9a-fA-F]{2}$/i;
With this I am able throw exception for ff:ff:ff:ff:ff:ff but I also need to throw an exception for 00:00:00:00:00:00. My pattern is not throwing an exception.
Could you please give me a pattern through which I should able to throw an exception for both ff:ff:ff:ff:ff:ff and 00:00:00:00:00:00.
var MACAddress = document.getElementById("MACAddress");
var MACRegex=new RegExp("^([0-9a-fA-F][0-9a-fA-F]:){5}([0-9a-fA-F][0-9a-fA-F])$");
MACRegex.test(MACAddress);
var re = /^(?!(?:ff:ff:ff:ff:ff:ff|00:00:00:00:00:00))(?:[\da-f]{2}:){5}[\da-f]{2}$/i;
// ^------------blacklist------------^ ^----------pattern---------^
re.test('ff:ff:ff:ff:ff:ff'); // false
re.test('ff:ff:ff:ff:ff:fe'); // true
re.test('00:00:00:00:00:00'); // false
re.test('00:00:00:00:00:01'); // true
// and of course
re.test('00:00:00:00:01'); // false
re.test('00:00:00:00:00:0g') // false
Oh if we are answering about validating mac, here is mine: but this still doesn't answer the question: how to prevent characters that don't make up a mac address.
function isValidMac(mac) {
var a = mac.split(':');
if (a.length !== 6) {
return false;
}
for (var i=0; i<6; i++) {
var s = "0x"+a[i];
if (s>>0 === 0 || s.length != 4) {
return false;
}
}
return true;
}
I think that while the other answers are all valid, they missed the keypress aspect of the OP's question.
While that might not be important in this instance, I believe that the UX can be improved.
I would suggest;
-validating length =12
-accepting {0-9,a-f,A-F},
-alert {g-z,G-Z) (invalid character)
-ignore all others (including Tab, cr, lf, crlf)
-confirm exit after the 12th character
-display 3 forms; raw, couplet, quad
I have not yet had a chance to code but will submit and amend on completion
My answer is:
^([0-9a-fA-F]{2}[:-]){5}[0-9a-fA-F][1-9a-eA-E]$

js backspace and counting how many digits

i have this code for counting how many digits where entered
var tnnod=0;
function telephone(e) {
if (tnnod<10) {
var key;
var keychar;
if (window.event) {
key = window.event.keyCode;
}
else if (e) {
key = e.which;
}
else {
return true;
}
keychar = String.fromCharCode(key);
if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27) ) {
return true;
}
else if ((("0123456789").indexOf(keychar) > -1)) {
tnnod+=1;
return true;
}
else if (keychar == "-") {
return true;
}
else
return false;
}
else
return false
}
but how do i remove 1 from the counter each time the backspace was hitted and the char that was deleted was a digit and not "-"
i have tried getting the key == 8 to do something but hitting the backspace doesn't really return anything for some reason
what can be the problem?
You don't have to detect specifically the backspace keypress. Try this:
var tn_count = 0;
function telephone(ev) {
var el = document.getElementById("telephone_number");
if(tn_count < 10) {
var key, keychar;
if(window.event) {
key = window.event.keyCode;
} else {
key = ev.which;
}
keychar = String.fromCharCode(key);
}
if(!keychar.match(/\d|-/)) { // only allow digits or "-"
return false;
}
// clean up any non-digit chars that get in here somehow
el.value = el.value.replace(/[A-Za-z]+/, '');
tn_count = el.value.replace("-",'').length; // get the digit length
return true;
}
The basic difference here is that instead of adding 1 every time the key is pressed, just updated tn_count to be the total count of all digit characters in the field. You can probably do some more cleanup just to be safe, but this should get you started.
I think it's a bad idea to count keystrokes for something like that. We're talking about input into a text field, right? What will you do if the user does a paste of some string from the clipboard? What if he uses the mouse to mark some text and delete it? Replace it with one character?
I think it would make a lot more sense to just look at the text from the text field and (if necessary) do some fiddling to ensure proper syntax. Let the user enter whatever he wants, if you find garbage characters you can just replace the text with one that doesn't have those characters. You can also trim the field at this time (no leading or trailing spaces). Also, keeping accurate track of the length becomes as easy as asking for the length of the string returned from the field.
A few thoughts -
Would it be possible to use 3 fields instead of 1? Then you could add the dashes later.
If you want to use your current method, you might keep a counter of the dashes that have been typed. Then, on each key stroke, check to see how many dashes are left. If it's different than the previous count, you know they've deleted the dashes.
I think it needs to be a bit more robust. What if they put a dash in an odd place within the string?
You could also prevent the user from entering all non-numeric characters and insert the dashes at each point of separation. So, insert a dash after 3 and 6 numbers as they are typing.
Could you just count the length of the string and use that value? Something like the following:
function getLen(el) {
return el.value.replace('-', '').length;
}
alert(getLen(document.getElementById('telephone_number')));

Categories

Resources