Mask input on html does not work - javascript

I'm trying to create a mask to my input, but one strange error happens. I have to enter 11 numbers, and my mask have to make it like this: ###.###.###-##. But when I enter the sixth digit my current input become blank. I have no idea what is the problem.
This is my script:
function mascararCpf(){
var cpf = document.getElementById("idCpf");
if((cpf.value.length == 3) || (cpf.value.length == 6)){
cpf.value += ".";
return;
}
if(cpf.value.length == 9){
cpf.value += "-";
return;
}
}
And this is my input:
<label> CPF: <input type="number" autocomplete="on" name="cpf" id="idCpf" placeholder="Seu CPF" required onblur="validarCpf()" onkeypress="mascararCpf()"></label>

Try with
<input type="text" ...
problem with the input type number
DEMO
If you want to open Numeric keypad on focus, I would suggest you to use
<input type="tel" ...
Another DEMO

That's because you need to count dots . as part of the length. "123.456" is SEVEN characters long.
It is a common practice to put several input fields (in your case 4 fields) and to go from one field to the other when the length of the field (3) has been reached.

As noted before the input type should be text. Furthermore, you should consider that the length of the input value increases after appending a '.' or '-'.
Your html is not valid. The <label>-tag should be closed before opening <input>.
It's better not to use inline handlers. You can assign your hander in the script. Using type="text" the input value can also be non numeric. If you want the mask-method to check that you should add checking of the inputted value. A tentative method could be:
// bind handler to the input field
document.querySelector('#idCpf').onkeypress = mascararCpf;
// the handler method, including a numeric-check for the entered value
function mascararCpf(e){
var len = String(this.value).length;
this.value += len === 3 || len === 7 ? '.' : len === 11 ? '-' : '';
return isNaN(+String.fromCharCode(e.keyCode)) ? false : true;
}
Here's a jsFiddle demonstrating it all

I had a similar need, so I developed the following code. Not 100% yet, but it works.
function editMask(mask,element,e) {
if (e.keyCode >= 48 & e.keyCode <= 57 | e.keyCode >= 96 & e.keyCode <= 105 | e.keyCode == 46 | e.keyCode == 8) {
var v = element.value;
var N = v.replace(/\D/g,'');
var L = N.length;
var r = '';
var resp = '';
for (i=0;i<mask.length;i++) {
if (mask[i] == '_') {
if (N.length > 0) {
r = N[0];
N = N.substring(1,N.length);
} else {
r = '_';
}
} else {
r = mask[i];
if (N.length > 0) {
L++;
}
}
resp = resp+r;
}
element.value = resp;
element.setSelectionRange(L,L);
}
}
It's called in the onkeyup event of the input:
<input type='text' size=20 id='insPFis_CPF' value='$CPF' onkeyup='javascript:editMask(\"___.___.___-__\",this,event)'>
You may want to change the mask format for CNPJ, phone numbers, etc. I hope it helps.

Related

Using regex to restrict input in textbox [duplicate]

This question already has answers here:
HTML input that takes only numbers and the + symbol
(7 answers)
Closed 5 years ago.
/^+{0,1}(?:\d\s?){11,13}$/ this regex allows + at first place only and numbers only...
on keypress I want user should only be able to type + at first and digits that what above regex validates But code always goes to if part..why regex not working in this scenario
function ValidatePhone(phone) {
var expr = /^\+?(?:\d\s?){11,13}$/;
return expr.test(phone);
}
var countofPlus = 0;
$("#phone").on("keypress", function (evt) {
if (evt.key == "+")
{
countofPlus = countofPlus + 1;
if (countofPlus > 1 || this.value.length >= 1) {
return false;
}
else return true;
}
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && charCode != 43 && charCode != 32 && charCode != 40 && charCode != 41 && (charCode < 48 || charCode > 57))
return false;
return true;
});
$("#phone").on("keyup", function (evt) {
debugger;
if (evt.key == "+") {
countofPlus--;
return true;
}
});
Adapting an answer from HTML input that takes only numbers and the + symbol to your use-case yields the following (IE-)compatible code:
// Apply filter to all inputs with data-filter:
var inputs = document.querySelectorAll('input[data-filter]');
for (var i = 0; i < inputs.length; i++) {
var input = inputs[i];
var state = {
value: input.value,
start: input.selectionStart,
end: input.selectionEnd,
pattern: RegExp('^' + input.dataset.filter + '$')
};
input.addEventListener('input', function(event) {
if (state.pattern.test(input.value)) {
state.value = input.value;
} else {
input.value = state.value;
input.setSelectionRange(state.start, state.end);
}
});
input.addEventListener('keydown', function(event) {
state.start = input.selectionStart;
state.end = input.selectionEnd;
});
}
<input id='tel' type='tel' data-filter='\+?\d{0,13}' placeholder='phone number'>
Above code takes copy & pasting, selecting, backspacing etc. into account where your current implementation fails.
Also, I modified the given regex to \+?\d{0,13} so it allows for incomplete input. Use HTML5 form validation to validate the final result.
I think this regex is being applied only to the char code i.e. a string of length 1. In this case regex will always fail.
Instead, try running the regex test on the input value.

Limit numbers before and after decimal point on input number

How to limit numbers for before and after the decimal point, something like 123.123 , so it can have max 3 numbers before . and max 3 numbers after .
<div class="form-group">
<input type="number" class="form-control" name="ta" id="ta" placeholder="ta" ng-model="ta.kol" ng-maxlength="15"/>
<p ng-show="taForm.kol.$error.maxlength" class="help-block">Max 15 symbols !</p>
</div>
You can add a onchange event on the input field and call a function that validates the current input value using regex and communicate same to the user.
Regex : ^[0-9]{0,3}.?[0-9]{0,3}$
JS Code to validate:
function validateNumberInput(inputNumber){
return number.search(/^[0-9]{0,3}.?[0-9]{0,3}$/) == 0 ? true : false;
}
Also you can write a directive in angular that can handle the same.
This can be solved with a simple piece of javascript if you just add an Event Listener to the input and then split the input on the decimal point you can then check the length of both parts and act accordingly.
https://jsfiddle.net/pk07net6/
function checkNumbers()
{
console.log(this.value);
var numbers = this.value.split('.');
var preDecimal = numbers[0];
var postDecimal = numbers[1];
if (preDecimal.length>3 || postDecimal.length>3)
{
alert("Max 3 numbers before and after the decimal point.")
this.select();
}
}
//ADD LISTENER TO INPUT
var input = document.getElementById("numberInput");
console.log(input);
input.addEventListener("change", checkNumbers)
You can use ng-pattern with a regex:
<input ng-pattern="/^[0-9]{1,3}(\.\d{0,3})?/" />
docs: https://docs.angularjs.org/api/ng/directive/ngPattern
For the fraction its pretty easy as you can use Angular number filter. As for the number before the digit you should create a filter like this :
app.filter('beforeDigit', function ($filter) {
return function (input) {
if (input>1000)
return (input % 1000)
elseif(input<1000)
return input;
};
});
So in the end you will end up with something like this :
{{val | filter:{number:3}, filter:beforeDigit }}
After hours of work, I create java-script function which work on keypress event. Number can be 8 characters before decimal separator and 2 character after decimal separator.
https://codepen.io/dumbelovic/pen/bvdXXq
function BeforeAfter(e, obj) {
sepDec = "."
var keycode;
var fieldval = obj.value;
if (window.event) keycode = window.event.keyCode;
else if (e) { keycode = e.which; }
else { return true; }
// denided first charatcter to be zero
if (fieldval == "" && keycode == 48)
return false;
// denided first character to be decimal point
if (fieldval == "" && (keycode == 44 || keycode == 46))
return false;
// enter first decimal point,
// but every next try to eneter decimal point return false
if (fieldval != "" && ((keycode == 44 || keycode == 46))) {
if (fieldval.indexOf(sepDec) < 0) {
var newValue = fieldval + sepDec;
$(obj).val(newValue);
}
return false;
}
var splitfield = fieldval.split(sepDec);
var beforeDecimalPoint;
var afterDecimalPoint;
if (splitfield.length == 1) {
beforeDecimalPoint = splitfield[0];
afterDecimalPoint = "";
}
else if (splitfield.length == 2) {
beforeDecimalPoint = splitfield[0];
afterDecimalPoint = splitfield[1];
}
if (beforeDecimalPoint.length == 8 && keycode != 8 && keycode != 0) {
if (obj.selectionStart >= 0 && obj.selectionStart <= 8)
return false;
}
if (afterDecimalPoint.length == 2 && keycode != 8 && keycode != 0) {
if (obj.selectionStart >= beforeDecimalPoint.length + 1 && obj.selectionStart <= beforeDecimalPoint.length + 1 + 2)
return false;
}
return true;
}

JavaScript error trapping is not reading 0 (zero)

The JavaScript below just checks if there are 4 digits in a field or not and then warns if there isn't.
But for some reason, if I enter four zeros (0000) it takes that as an empty field and throws the warning.
Any idea how to fix this...?? I am no programmer but have put this code together after weeks of trial-and-error.
function validate(){
// if ( (!isNaN($("#couponstart1").val())) || (!isNaN($("#couponstart2").val())) || (!isNaN($("#couponend1").val())) || (!isNaN($("#couponend2").val())) ) {
var all_ok = true;
var err_msg = "";
var fld = "";
if ( $("#couponstart1").val() == '' || $("#couponstart2").val() == '' || $("#couponend1").val() == '' || $("#couponend2").val() == '' ) {
all_ok = false;
err_msg += "\n - Card Numbers cannot be blank";
fld='couponstart1';
}else{
if ( isNaN($("#couponstart1").val()) || isNaN($("#couponstart2").val()) || isNaN($("#couponend1").val()) || isNaN($("#couponend2").val()) ) {
all_ok = false;
err_msg += "\n - Card Number has to be numeric";
fld='couponstart1';
}else{
if ( $("#couponstart1").val() < 1 || $("#couponstart2").val() < 1 || $("#couponend1").val() < 1 || $("#couponend2").val() < 1 ) {
all_ok = false;
err_msg += "\n - Card Numbers are not correct";
fld='couponstart1';
}else if ($("#couponstart1").val().length != 4 || $("#couponstart2").val().length != 4 || $("#couponend1").val().length != 4 || $("#couponend2").val().length < 4){
all_ok = false;
err_msg += "\n - Card Numbers are not correct";
fld='couponstart1';
}
}
}
if (all_ok == false){
alert("The following errors have taken place" + err_msg);
setFocus(fld);
}
return all_ok;
}
It's sad that computers do what we ask, not what we want.
If your input is filled with 0000, and you compare < it with the number 1: ($("#couponstart1").val() < 1, javascript will try to parse the value 0000 to the operand type which accounts to 0. So it is right to say that 0 is lower than 1and you'll get your error message Card number are not correct.
Let's try a different approach:
<!-- html -->
<form>
<p>
<label for="couponstart1">Coupon Start Part 1</label>
<input type="text" maxlength="4" id="couponstart1" class="validateme" />
</p>
<p>
<label for="couponstart2">Coupon Start Part 2</label>
<input type="text" maxlength="4" id="couponstart2" class="validateme" />
</p>
<p>
<label for="couponend1">Coupon End Part 1</label>
<input type="text" maxlength="4" id="couponend1" class="validateme" />
</p>
<p>
<label for="couponstart2">Coupon Start End 2</label>
<input type="text" maxlength="4" id="couponend2" class="validateme" />
</p>
<button type="button" id="testit">Test</button>
</form>
and:
/* javascript/jQuery */
$(document).ready(function(){
$("#testit").click(function(){
var rgx = /\d{4}/;
var allgood = true;
$("input.validateme").each(function(){
if( ! rgx.test( $(this).val() ) ){
alert("Card number for " + ($('label[for="' + $(this).attr("id") + '"]').text()) + " is not correct!\nPlease use 4 digits all numbers!");
$(this).select();
allgood = false;
return false;
}
});
if(allgood) alert("All good!");
});
});
Basically we have a form with 4 inputs with "validateme" class.
With jQuery we loop over the inputs that have this class an run it against the regex /\d{4}/ which basically will test for a number(\d) exactly 4 digits long ({4}) meaning from 0000 to 9999. Note that we use the label of the input to identify which field is not right.
Otherwise, all good.
You can fiddle with this code here: http://jsfiddle.net/L8dcgcrs/1/
Assuming the four digits correspond to $("#couponstart1").val(), $("#couponstart2").val(), $("#couponend1").val(), $("#couponend2").val() then the problem is that in JavaScript there are two types of comparison operators.
In your first if statement you choose to evaluate if $("#coupontstart1").val() == '' || ...). In this case you are using an equality operator which converts the operands if they are not the same type. So using this operator 0 == '' returns true. Instead you could use the strict equality operator === in the following manner:
if ( $("#couponstart1").val() === '' || ...)
In which case 0 === '' would return false. This most likely will help you in the first if statement you write as entering 0000 would make all the conditions false and you would proceed to the else block.
Hope this helps!

Javascript - handling keypresses in order?

I have a simple "onKeyUp" Javascript routine that is supposed to handle adding dashes to an input field to format a phone number, turning "1234567890" into "123-456-7890". However, if the user types too fast the routine apparently doesn't fire, or the event gets lost, I'm not sure. But in that case, the dashes don't get inserted.
Can anyone suggest a fix for this? Here's the routine:
function(event, field) {
// Don't add dashes if user pressed backspace
if (event.keyCode != 8 ) {
if (field.value.length == 3 || field.value.length == 7) {
field.value = field.value + "-";
}
}
};
SOLUTION
var dashes = function(event, field) {
if (event.keyCode != 8 ) {
var arr = field.value.split(''),
l = arr.length;
if(l > 2 && arr[3] != "-") arr.splice(3, 0, "-");
if(l > 6 && arr[7] != "-") arr.splice(7, 0, "-");
field.value = arr.join('');
}
};
var input = document.getElementById('in');
input.addEventListener('keyup',function(event){
dashes(event, input);
});

JavaScript: Restricting fields - cannot remove special symbols

I am trying to restrict an input text to numbers only by checking it in a setInterval and removing the chars that are not numbers. Now so far this works relatively alright, however I am not able to remove "special symbols". For example if I input the Spanish accent symbol ' or symbols like ˇ that should be over a char, it resets the field and the value is not assigned again despite the fact that the symbol gets removed from the string (if I log the string, I can see it is).
Example:
Typing 123a => 'a' removed, input contains 123
Typing 123ˇ => input contains an empty string, despite the fact that the 'text' string
contains 123 and has a length of 3.
Typing 123 and pasting ˇ after it => ˇ removed, input contains 123
This seems like it has something to do with the fact that the special symbols are not ...self-standing (?) and need to be over a char that should be inputted next. Some ideas how to solve it?
Thank you.
I have the following HTML:
<body>
<input type="text" id="input_field">
</body>
And the JS:
$("#input_field").focus(function(e) {
console.log("got focus"+$(this).val());
var obj = this;
intID = setInterval(function() {restrictNumbers(obj)}, 10);
});
$("#input_field").blur(function(e) {
console.log("got blur")
clearInterval(intID);
});
function restrictNumbers(field) {
var text = $(field).val();
var caretPos;
var modified = false;
if(text.length > 0) {
for(var i=0; i<text.length; i++) {
if(isNaN(text.charAt(i))) {
modified = true;
caretPos = field.selectionStart - 1;
text = text.replace(text.charAt(i), "");
i--;
}
}
$(field).val(text);
if(modified) {
modified = false;
field.setSelectionRange(caretPos, caretPos);
}
}
}
JSfiddle example: http://jsfiddle.net/AvMZ5/
You can use this:-
jQuery.fn.ForceNumericOnly =
function()
{
return this.each(function()
{
$(this).keydown(function(e)
{
var key = e.charCode || e.keyCode || 0;
// allow backspace, tab, delete, arrows, numbers and keypad numbers ONLY
// home, end, period, and numpad decimal
return (
key == 8 ||
key == 9 ||
key == 46 ||
key == 110 ||
key == 190 ||
(key >= 35 && key <= 40) ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
});
});
};
You can then attach it to your control by doing:
$("#yourTextBoxName").ForceNumericOnly();
Source:- https://gist.github.com/wholypantalones/3083362

Categories

Resources