I am using max length to limit my input to 6 numbers. The issue is it stops after 6. I think the issue is with the regex match I am using to separate the input and the max length.
<input type="text" ng-keyup="addHyphen($event)" id="sortcode" name="sortcode" maxlength="6" ng-model="data.branchTransitNumber" required numbers-only/>
Script:
$scope.addHyphen = function() {
// $scope.dashed= angular.element($event.target.value);
var ele = document.getElementById('sortcode');
ele = ele.value.split('-').join('');
$scope.data.branchTransitNumber = ele.match(/.{1,2}/g).join('-');
};
Expected in input: 11-11-11
Currently: 11-11-1
I am also not receving any console errors also.I think the regex wants to put - after two numbers and max length won't allow additional input.
EDIT:
After removing the max-length its is working. But how to make it work along with max-length
#Duck_dragon, maxlength attribute is used to restrict user to enter specified no. of characters. here you have set maxlength="6" thats why it will only allow six characters in input box. Note here it also consider - in calculation.
so if you want to allow input like 11-11-11 then you have to set maxlength="8"
Related
I have a dynamic grid that has a numeric field in which I have applied masking. Also it has a plus button means the user can add many rows as he wants. The masking is applied like this:
<input type='textbox' placeholder='00000-00-000' data-mask='00000-00-000'
This masking is applied when the user enters 10 digit number but it lets the user enter a 2 or 3 digit number as well. For this I am trying to apply validation while saving so that it checks whether the value entered matches the required format.
What I have done so far is :
value = $(this).find('td:eq(1)').find('input').val(); //saves the entered value in a variable value
myRegExp = new RegExp(/\d{5}-\d{2}-\d{3}/);
if (!myRegExp.test(value)) {
valid = false;
}
else
valid = true;
The value that user enters is saved in varaible called value and then I have defined my Regex Expression to match my value with that expression but somehow this regex expression is not working. Is this the correct way to define regex expression? What am I missing here? My required format is 00000-00-000. Any help would be appreciated.
Your logic is correct but you have not defined the end point that's why it allows to insert more values.
In your Regex it only checks if the 10 digits are in the specific order
try out this
myRegExp = new RegExp(/^\d{5}-\d{2}-\d{3}$/);
I have an input tag of type number with pattern validation attached to it that has at least taken care of eliminating the 'e' '+' '-' characters from being input. However the '.' symbol still gets through for some reason. Here are the relevant portions of code from my program:
<input type="number" id="job-priority" min="1" max="99" pattern="[0-9]+" placeholder="1 (High) — 99 (Low)" style="width:186px; padding-left:14px; text-align:center;">
document.getElementById('job-priority').addEventListener('input', function () {
// Check that characters typed into job priority field are valid.
if (!document.getElementById('job-priority').validity.valid) {
var value = document.getElementById('job-priority').value;
value = value.slice(0,-1);
document.getElementById('job-priority').value = value;
}
});
document.getElementById('job-priority').addEventListener('change', function () {
// Check that number entered into job priority stays within limits.
var value = Number(document.getElementById('job-priority').value);
var min = Number(document.getElementById('job-priority').min);
var max = Number(document.getElementById('job-priority').max);
if (value < min)
document.getElementById('job-priority').value = min;
else if (value > max)
document.getElementById('job-priority').value = max;
});
From my own research on this up to this point, I have come across one previous question post on StackOverflow regarding input patterns with input type number. That post, in short, confirms that input patterns don't work for input type number. It proposes the solution to just use input type text instead with a pattern to allow only numbers through. However, I want to keep the input type to number because of the up/down arrows that increase/decrease the number in the input field. I would be willing to change the input type to text only if their is a way to keep the up/down arrows in question.
I also see that if I remove the pattern from the input tag, my event listener for 'input' still successfully takes care of not allowing the 'e' '+' '-' characters somehow. Of course, the '.' symbol is still being allowed when it shouldn't. So I guess at least I confirmed that the pattern wasn't actually doing anything from what I can tell.
More specifically, if the '.' is typed as the first character, the validation check successfully works and nothing appears in the input field which is the desired behavior. However, if the first character typed is a number and then second character typed in is the '.' symbol, then for some reason the '.' symbol appears when it should not have.
Figured out a solution to my problem.
document.getElementById('job-priority').addEventListener('input', function () {
// Check that characters typed into job priority field are valid.
document.getElementById('job-priority').type = 'text';
if (!document.getElementById('job-priority').validity.valid) {
var value = document.getElementById('job-priority').value;
value = value.slice(0,-1);
document.getElementById('job-priority').value = value;
}
document.getElementById('job-priority').type = 'number';
});
You'll see that what I did was change the input type to 'text' temporarily just for the input validation. Then, as soon as it's done, immediately change the input type back to 'number'.
I have 5 text boxes I will get prices how can I validate there is only numbers on those text boxes if there is a letter I want to give a alert when submit.
How can I do that please help me Im new to these stuff
<input type="text" id="sellingPrice"><br>
<input type="text" id="basicPrice"><br>
<input type="text" id="latestBuyingPrice"><br>
<input type="text" id="ReorderQuantity"><br>
<input type="text" id="reorderLevel"><br>
<button id="save_P" type="button" class="save-button-text save-button displayShow" onclick="submitDetails()">
how can I use number validation in submitDetails() method
This is a pretty common issue, but there are a couple ways to approach it:
Verify using Regular Expressions
Attempt to parse the number and check if isNaN(parsedResult) returns true
By far, I believe the most common approach is var num = parseFloat(StringNumberFromTextbox), isValidNumber = (!isNaN(num) && isFinite(num));
If you went the RegEx route, you could use: var rNumPattern=/^\d+(\.\d+)?$/, isValidNumber = rNumPattern.test(StringNumberFromTextbox);
You might also consider consider checking negative/positive signs and thousands separators using replacements of commas or periods (as appropriate for the locale/clientele).
Of course, if you are then submitting those on a form to some backend processor, you would be wise to check those numbers again on the server-side rather than blindly trusting that the client has provided valid numbers just because your JavaScript should done the checking. Lest you end up with a SQL vulnerability or the like.
You can add type="number" attribute to input tag.
In submitDetails() use following code.
var sellingPrice=document.getElementById("sellingPrice").value;
//repeat above code for all field.
if(Number.isInteger(sellingPrice) == false){
alert('wrong value entered');
}
//repeat above if code for all value.
This will do what you want.
You can check it using isNaN(value) inbuilt function of JavaScript.
Your function could be like this:
function submitDetails() {
var val = document.getElementById("sellingPrice").value;
if (isNaN(val)) {
// show alert here
}
}
I have a numeric textbox, by default numeric textbox allows Exponents and periods.
How do i restrict that?
One of the method i can think of is using string.replace on input event however it is not working as expected. Below is my code..
HTML
<input type='number' class='number'>
JavaScript
$(".number").on('input', function () {
this.value = this.value.replace(/e|E|\./g, ''); // Remove e, E, and period(.)
if (this.value.length > 4) {
this.value = this.value.slice(0, 4);
}
});
When i enter string '2e' in textbox, entire input is getting removed if above code is ran. i just wants to remove e, E or period from input string not entire input.
Is there a way to achieve this.
JSfiddle
Answer BY nichel is working like a charm, now my problem is how do i restrict the same in PASTE event.?
So basically you want to allow just numbers? Then restrict the keys by keycode & remove excess chars on paste
$(".number").keypress(function(e){
return e.keyCode>47&&e.keyCode<58;
}).paste(function(){
$(this).val($(this).val().replace(/\D/g,''));
})
And since you'd like the max length to be 4, just add max="9999":
<input type='number' class='number' max="9999">
input[type=number] returns ""(blank string) if input value is not valid.
You can refer this post for more information.
I would suggest you to use input[type=tel] instead. It also has a maxLength attribute so you so not have to worry about trimming extra values.
You can even replace your regex to /[^0-9]/. This will replace all characters except numbers.
Sample Fiddle.
So you final code would look like: JSFiddle
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");
});