JavaScript mask for Brasil phone number - javascript

Currently I'm using jquery.maskedinput for verious mask formats, but it's not working for phone numbers.
In Brasil we used to have all numbers in the format (99)9999-9999. But lately, in a few cities, cell phones are using (99)99999-9999, while their normal phones and the rest of the country remain (99)9999-9999.
jquery.maskedinput seems to not support 2 formats on the same input where a character in the middle of the string may or may not be present. As I can see in its documentation, I could have (99)9999-9999 and (99)9999-99999, but that would confuse users.
Is there any other mask plugin/framework that allows me to validate both (99)9999-9999 and (99)99999-9999?
Edit: I created a full test using harry and Dmitrii solutions: http://jsfiddle.net/NSd6g/ $('#full').inputmask('(99)9999[9]-9999');
I'm gonna wait a bit more to see if I can find an even better solution. The perfect one wouldn't require the red message, second group would have 4 digits by default. And, if third group would get a fifth digit, only then second group would get its fifth space, moving third group's first digit into second group's fifth. lol kinda hard to understand, sorry!

You could achieve this using jquery.inputmask as simple as:
jQuery(function($) {
$('#test').inputmask('(99)9999[9]-9999');
});
Try this demo.
To skip the optional part while typing into the input you need to type space or the char following the optional part in the mask (hyphen in this case).

I'm Brazilian too.
At my job we don't actually use the "-" char in the middle for those type of masks, so there's no confusion... the final mask would be the following: (99)99999999?9
It's a bit harder to the final user to identify a wrongly typed phone number this way, but it works.
Another way I know is building the regex in JS and then using it with another plugin, like, for example, jQuery Validate.

With jQuery mask you can only have the trailing characters be optional. Not ones in the middle on the input.
My suggestion would be to have 3 input boxes, one for each part of the number with the optional character at the end of the middle input. Then concatenate the inputs on submit.
like so:
(<input id="phone2" />)<input id="phone3" />-<input id="phone4" />
jQuery(function($){
$("#phone2").mask("99");
$("#phone3").mask("9999?9");
$("#phone4").mask("9999");
});
See fiddle: http://jsfiddle.net/Rge83/1/
To make it more user friendly, a script to move to the next input once the current one has been filled can be added + some css to make the inputs look more like one.

My suggestion: "(99) [9] 9999-9999"

//Configuração para celular com nono digito
$('#Seletor').focusout(function () {
var phone, element;
element = $(this);
element.unmask();
phone = element.val().replace(/\D/g, '');
if (phone.length > 10) {
element.mask("(99) 99999-999?9");
} else {
element.mask("(99) 9999-9999?9");
}
}).trigger('focusout');

Some updates 10 years later:
jQuery is still alive (yes!)
all mobiles in Brazil have 9 digits now (besides 2 digits from area code)
all Brazilian landlines still have 8 digits (besides area code)
So in order to have a field accepting both mobiles or landlines I prefer a dynamic mask that will automatically adjust itself to "5+4" or "4+4" depending on how many digits were typed.
Example:
$('#ContactPhone')
// by default we expect a mobile (5+4 digits)
// so the initial mask splits 5+4 and if someone pastes 9 digits
// the separator position won't be changed causing a blip
.inputmask('(99) 99999-999[9]')
.on('change keyup paste', function () {
var digits = $(this).val().replace(/\D/g, '').length;
// ... if there are only 8 digits we reformat as 4+4 -
// but yet letting space for another digit (which would reformat the mask back to 5+4)
if (digits == 10)
$(this).inputmask('(99) 9999-9999[9]');
else
$(this).inputmask("(99) 99999-9999");
});

Related

Regex to match only certain characters or strings and only one instance of each?

I feel like I know just enough about Regexes to get stuck. That said, I have an input field which will allow users to enter their currency symbol. I'm only wanting to allow said currency symbol and disallow anything else from being entered into that field. Some countries don't actually have a single symbol, but are just two or three characters, e.g., "Kr" for Krona. So the field has a max length of 3. Given it needs a max length of three to accommodate some currencies, I also don't want to allow three dollar signs to be entered, e.g., "$$$". I would only want to allow one single dollar, pound, euro, etc. sign.
Here's my basic code for allowing only these symbos in the input:
$('#id_currency_symbol').on('input',function (){
var value = $(this).val().toString();
newvalue = value.replace(/[^$£€¥₣₩₩¥₽₺₹Rkr]+/g,'');
$(this).val(newvalue);
});
This works for only allowing these symbols/letters, but like I said above, I don't want to allow users to enter more than a single instance of some symbols, i.e. dollar sign ($). In addition, I want to match exact strings for cases where the "symbol" is actually just two or three characters. In the case of Krona, the "symbol" is Kr. Given the above, users could in theory enter "rK" and it would be perfectly valid according to the regex, but I would ONLY want to allow the exact match of "Kr." Is that possible?
Thanks
I would suggest to forget regex, and go for O(1) algos,
var allowedCurrencyCodes = {
"$":true,
"¢":true,
"£":true,
"INR":true,
"Kr":true,
.....,
.....,
.....
}
$(this).val(allowedCurrencyCodes[$(this).val()]?$(this).val():"");
you need to perform the check at blur event or when user has entered at least 3 chars, else it becomes buggy as it will keep on wiping the data right after first char.
if you want to keep check real time i.e. responsive when user is typing in, then you need to change the structure of allowedCurrencyCodes and convert it to nested object for multi-char currency codes, e.g $,£ would be exactly same but INR or Kr will be defined like
"I":{
"N":{
"R":true
}
},
"K":{
"r":true
}
and minor change in fetch logic will be applied, where you will capture input and split it in array and then dip in allowedCurrencyCodes based on input chars, like
allowedCurrencyCodes[inputChar[0]][inputChar[1]]
or
allowedCurrencyCodes[inputChar[0]][inputChar[1]][inputChar[2]]
You may find the first occurrence of a currency symbol or acronym using a regex and then replace the whole input with the matched string. Single character currencies can be listed in [...] and any longer string may be added by alternation:
var checkInput = function(input) {
var regex = /[$£€¥₣₩₩¥₽₺₹]|kr/i;
input = regex.exec(input);
return input == null ? "" : input[0];
}
console.log(checkInput("lkjahfkdshfjsdf Kr asdasda"));
console.log(checkInput("kr"));
console.log(checkInput("rk"));
console.log(checkInput("$$$"));
console.log(checkInput("₣₩₩"));
console.log(checkInput("ABC"));
For completeness:
The "Regex to match only certain characters or strings and only one instance of each":
^(?:[$£€¥₣₩₩¥₽₺₹]|kr)$
Demo: https://regex101.com/r/w9p9d9/1
Regex to strip off anything but "certain characters or strings" and these characters too if they appear more than once (for use within newvalue = value.replace(...,'');):
^(?=.*?([$£€¥₣₩₩¥₽₺₹]|kr)|).*
Demo: https://regex101.com/r/qocsv5/1

Special dot masked input HTML-JavaScript

I'm trying to achieve a special masked input in HTML using jQuery and themask plugin from Igor Escobar (http://igorescobar.github.io/jQuery-Mask-Plugin/)
I need write only numbers[0-9] and the following conversions:
input:
123456789
12345678
1234567
123456
desidered output:
123.456.789
12.345.678
1.234.567
123.456
Is possible achive this with that plugin?
Or exist another way to do it?
Thanks for reading :)
EDIT:
I did it using another plugin (Numeral.js):http://numeraljs.com/
This is my working code:
$("#myinput").blur(function()
{
this.value=numeral(this.value).format('0,0[.]00').replace(/\,/g, '.');
});
But I do not like to be validated at the end, ie (onblur), is there any way to do this on the fly? - That is, gradually validate (keypress).
You probably don't need a library for that. I kept jQuery but it's really used to select the input, so you definitely can ditch it quite easily.
$("#myinput").keyup(function(){
// prevent every character except numbers
if(!this.value.slice(-1).match(/^[0-9]+\.?[0-9]*$/) ){
this.value = this.value.slice(0, -1);
return;
}
// remove the dots, split the string and reverse it
var a = this.value.replace(/\./g, '').split('').reverse();
// start from 3 and as long as there's a number
// add a dot every three digits.
var pos = 3;
while(a[pos] !== undefined){
a.splice(pos,0,'.');
pos = pos + 4;
}
// reverse, join and reassign the value
this.value = a.reverse().join('');
});
You can try it yourself here and see if it does the job. Hope it helps.
EDIT: while the above code works it has some shortcomings, such as:
it does not work when copy/pasting
it does not allow moving with arrow keys
the cursor always goes to the end of the input, even when you are inserting a number in the middle.
As I needed it with full support for those cases I evolved it in a tiny script you can find on Github along with a demo and test spec.
$("#myinput").on('keyup keydown blur', function() {
this.value=numeral(this.value).format('0,0[.]00').replace(/\,/g, '.');
}

how to validate a text field in jsp using java script for accepting only dot and comma as special characters

I need to allow only numerics, dot and comma in a text field. If the user enters other special characters an alert needs to be thrown.
Please find below the conditions:
The text field should contain atleast one numeric value.
It is not mandatory that the text field should contain dot and comma always.
Thanks for your help.
Here is a start for you: http://jsfiddle.net/KLyy8/1/
Unless you tell us the exact specifics we won't know how to write the regular expression. Sounds like you want numbers with thousands separator and decimals. But how many of each? The fiddle above will work for numbers like this...
123,456.79
12,345.6
1,234.56
etc...
validate=function(){
var str = document.getElementById('test').value;
var patt = new RegExp("^[0-9]{1,3}\,[0-9]{3}\.[0-9]{1,2}$");
var res = patt.test(str);
alert(res);
}
If the field should contain only numeric values with decimal places (for exmaple 3.14, 112358 or 9,81), then you can use only one regex:
function validateString(str){
if(str.match(^[0-9\.,]+$)){
return true;
}else{
return false;
}
However if you want to be precise you will probably want to limit the dots and commas to one, if I understand your situation correctly.
Regex for that can look like this
^[0-9]+(\.|,){0,1}[0-9]+$
That means it starts with a number (^[0-9]+), then it may contain zero or one times one comma or dot ((\.|,){0,1}) and then again ends with a number ([0-9]+$).

how to use javascript to check if the first character in a textbox is a number?

I'm making a simple form and having a textbox for street address....
All I want to do is check if the first value entered is a number or not.
How can I do it?
if(document.forms[0].elements[2].value.
that is all I have now but I'm not sure what I should add to it to check the first character only.
As you said in your question you want to check for the first character only, you can use charAt function for string to check whether the first character is from 0 to 9 or any other check you want for the first character
Possible solution
var firstChar = document.forms[0].elements[2].value.charAt(0);
if( firstChar <='9' && firstChar >='0') {
//do your stuff
}
This can simply use isNaN. Just put a bang before it to check if it is a number, instead of isNaN's normal use of checking if it isn't a number, like so:
var val = document.forms[0].elements[2].value;
if (!isNaN(val.charAt(0))){ //If is a number
//Stuff
}
This also goes with numbers as strings, so need to worry about quotes or any of that hoo ha.
You can use if (document.forms[0].elements[2].value.match(/^\d+/)) to check if the beginning of the field is composed by numbers.
It will match for:
0 - valid
1 - valid
1a - valid
1 a - valid
1234567 - valid
a - invalid
a1 - invalid
Literally anything that start with numbers.
You can extend its functionality to if (document.forms[0].elements[2].value.match(/^\d+ +.+/))
In this form it will now require that its a number, plus one or more spaces, followed by anything else.
0 - invalid
1 - invalid
1(space) - invalid
1 1 - valid
1 a - valid
12345 abcdef - valid
Read more about Regular Expressions to elaborate complexier checkings.
But remember first that not every address has numbers, and most countries in the world don't use this format of writing addresses. As for the address field, I believe you should leave it open to be written in however format the user wish.

Using Regular Expressions with Javascript replace method

Friends,
I'm new to both Javascript and Regular Expressions and hope you can help!
Within a Javascript function I need to check to see if a comma(,) appears 1 or more times. If it does then there should be one or more numbers either side of it.
e.g.
1,000.00 is ok
1,000,00 is ok
,000.00 is not ok
1,,000.00 is not ok
If these conditions are met I want the comma to be removed so 1,000.00 becomes 1000.00
What I have tried so is:
var x = '1,000.00';
var regex = new RegExp("[0-9]+,[0-9]+", "g");
var y = x.replace(regex,"");
alert(y);
When run the alert shows ".00" Which is not what I was expecting or want!
Thanks in advance for any help provided.
strong text
Edit
strong text
Thanks all for the input so far and the 3 answers given. Unfortunately I don't think I explained my question well enough.
What I am trying to achieve is:
If there is a comma in the text and there are one or more numbers either side of it then remove the comma but leave the rest of the string as is.
If there is a comma in the text and there is not at least one number either side of it then do nothing.
So using my examples from above:
1,000.00 becomes 1000.00
1,000,00 becomes 100000
,000.00 is left as ,000.00
1,,000.00 is left as 1,,000.00
Apologies for the confusion!
Your regex isn't going to be very flexible with higher orders than 1000 and it has a problem with inputs which don't have the comma. More problematically you're also matching and replacing the part of the data you're interested in!
Better to have a regex which matches the forms which are a problem and remove them.
The following matches (in order) commas at the beginning of the input, at the end of the input, preceded by a number of non digits, or followed by a number of non digits.
var y = x.replace(/^,|,$|[^0-9]+,|,[^0-9]+/g,'');
As an aside, all of this is much easier if you happen to be able to do lookbehind but almost every JS implementation doesn't.
Edit based on question update:
Ok, I won't attempt to understand why your rules are as they are, but the regex gets simpler to solve it:
var y = x.replace(/(\d),(\d)/g, '$1$2');
I would use something like the following:
^[0-9]{1,3}(,[0-9]{3})*(\.[0-9]+)$
[0-9]{1,3}: 1 to 3 digits
(,[0-9]{3})*: [Optional] More digit triplets seperated by a comma
(\.[0-9]+): [Optional] Dot + more digits
If this regex matches, you know that your number is valid. Just replace all commas with the empty string afterwards.
It seems to me you have three error conditions
",1000"
"1000,"
"1,,000"
If any one of these is true then you should reject the field, If they are all false then you can strip the commas in the normal way and move on. This can be a simple alternation:
^,|,,|,$
I would just remove anything except digits and the decimal separator ([^0-9.]) and send the output through parseFloat():
var y = parseFloat(x.replace(/[^0-9.]+/g, ""));
// invalid cases:
// - standalone comma at the beginning of the string
// - comma next to another comma
// - standalone comma at the end of the string
var i,
inputs = ['1,000.00', '1,000,00', ',000.00', '1,,000.00'],
invalid_cases = /(^,)|(,,)|(,$)/;
for (i = 0; i < inputs.length; i++) {
if (inputs[i].match(invalid_cases) === null) {
// wipe out everything but decimal and dot
inputs[i] = inputs[i].replace(/[^\d.]+/g, '');
}
}
console.log(inputs); // ["1000.00", "100000", ",000.00", "1,,000.00"]

Categories

Resources