I'm trying to find a way to validate a text input on key press, I want to allow numbers only inside my text input including decimals.
I was taking the approach of using jQuery.keydown, and checking what the key was and using.
input numbers max length 999.999
-
my result after . (point) 3 number it is goog. but 99999.999
I need 999.999,222.222,22.01 ->
max length +++.+++
this my code
<input type="text" id="spinEdit2" class="aSpinEdit" />
<script type="text/javascript">
var txt = document.getElementById('spinEdit2');
txt.addEventListener('keyup', myFunc);
function myFunc(e) {
var val = this.value;
var re1 = /^([0-9]+[\.]?[0-9]?[0-9]?[0-9]?|[0-9])/g;
val = re1.exec(val);
//console.log(val);
if (val) {
this.value = val[0];
} else {
this.value = "";
}
}
</script>
Thanks
How about
/^([0-9]{1,3}(?:\.[0-9]{0,3})?)/g
In case you want the details: the {1,3} means the preceding thing can happen from 1 to 3 times. The (?:) is a non-captured group -- it's a grouping of the following symbols, but it doesn't capture to any variables like $1.
Related
I want to validate an input in real time way.
The input has type text and must validate only an input having : number(s) and/or floating point or comma.
Also the input accepts only two numbers after the floating point/comma.
Examples :
- 12.23 Valid
- 12,23 Valid
- 12.2 Valid
- 12,02 Valid
- 2 Valid
- 12.035 Invalid
- 12.36E Invalid
- test Invalid
I suggest tracking the live input validation with a /^(\d*)([,.]\d{0,2})?$/ regex that allows typing any 0 or more digits at the start, and then an optional substring of , or . and then 0, 1 or 2 digits. If there is a match, re-format the value by replacing , with .. If there input value is not matched, replace it with the last good value (say, introduce a variable called prevValue for that).
Once you want to submit this value, you need to make sure the value is in the final format, that is, there should be no . at the end. To enable this, add a pattern attribute to your <input> and assign the ^\d+(?:\.\d{1,2})?$ regex to it. Here, it will already require 1+ digits at the start of the string, and then will match an optional substring of a . followed with 1 or 2 digits. See the regex demo. Since the comma will get replaced with a dot, you need no [.,] pattern, \. is enough.
Also, it is a good idea to handle the input value change on paste.
var prevValue = "";
var patt = /^(\d*)([,.]\d{0,2})?$/;
function validateCurrencyPattern(price){
var matchedString = price.match(patt);
if (matchedString) {
prevValue = matchedString[1] + (matchedString[2] ? matchedString[2].replace(",", ".") : "")
return prevValue;
}
else {
return prevValue;
}
}
$(document).on("keypress keyup blur paste","#field", function (event) {
$(this).val(validateCurrencyPattern($(this).val()));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input type="text" id="field" name="field" pattern="^\d+(?:\.\d{1,2})?$"/>
<input type="Submit"/>
</form>
Since I did not find the solution on stack and spent some hours to develop a solution that can help others i'll share what i've done :
I used the RegExp pattern to validate the number.but i can't do it with one pattern so i've created two patterns.
The first validates: x*.yy
And the second validates: x*,yy
Constraints : isNumeric doesn't accept float with comma.so that's why i've converted it.
The function validation function code :
and The call for function mixing the events (keypress keyup blur)
function validateCurrencyPattern(price){
var patt = new RegExp(/[0-9]+[.]{1}[0-9]{2}/i);
var convertedPrice =price.replace(',', '.');
var matchedString = price.match(patt) ;
var matchedString2 = convertedPrice.match(patt) ;
if (matchedString) {
return matchedString
}
if (matchedString2) {
return matchedString2
}
if((!$.isNumeric(convertedPrice))|| convertedPrice<0){
return null;
}
else if(!matchedString && !matchedString2){
return convertedPrice;
}
}
$(document).on("keypress keyup blur","#field", function (event) {
$(this).val(validateCurrencyPattern($(this).val()));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="field" name="field">
Feel Free to optimize this solution or suggest another alternative that may be better than the existing solution.
I want to format my <input id="phone_number" type="tel"> on keypress
The requirements of my input field are:
numbers only and no letters and other special characters
format the input field with a US number like (123) 457-7890
This is my current code:
jQuery("#phone_number").on("keypress", function(event) {
var reg = /[0-9]/g;
var key = String.fromCharCode(event.keyCode);
if(!reg.test(key)){
// return false if NOT number
return false;
} else {
// numbers only
var phone_value = jQuery("#phone_number").val();
var number = phone_value.replace(/(\d{3})(\d{3})(\d{2})/,"$1-$2-$3");
jQuery("#phone_number").val(number);
}
});
Problem: The problem with my code is that it is not able to limit length of my input
Final Output should look like (123) 457-7890 first 3 digits enclosed in a parentheses
Any help is greatly appreciated. Thanks
I guess this should give you what is needed. You were very close to the answer.
I have limited the length of <input> using the maxlength attribute and added parenthesis in your phone_value.replace() function surrounding $1.
jQuery("#phone_number").on("keypress", function(event) {
var reg = /[0-9]/g;
var key = String.fromCharCode(event.keyCode);
if(!reg.test(key)){
// return false if NOT number
return false;
} else {
// numbers only
var phone_value = jQuery("#phone_number").val();
var number = phone_value.replace(/(\d{3})(\d{3})(\d{2})/,"($1) $2-$3");
jQuery("#phone_number").val(number);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="phone_number" type="tel" maxlength="14">
In below snippet code, If i give inputs "9999999999" and "9999999999." in console log both displays the same result "999999999" with out dot.
Am trying to capture dot symbol even after number. Here, only input type number is allowed cannot use text or any other type.
Text box is for number
Number: <input type='number' id=txtNumber'/>
And it's javascript function
$(document).ready(function() {
$('#txtNumber').keyup(function () {
var numbers = $(this).val(); console.log("numbers", numbers);
});
});
code at JSFiddle
Please help to find solution.
The reason is you set type='number'.
I suggest you set type='text' and use regular expressions to check if the value in the input is a number(include dot) or not:
$(document).ready(function() {
$('#txtNumber').keyup(function () {
if ($(this).val().match(/^[0-9]*\.?[0-9]*$/)){ //check if your value is number or not
var numbers = $(this).val(); console.log("numbers", numbers);
}
});
});
You can use a function to do this:
$(document).ready(function () {
$('#txtNumber').keyup(function () {
var numbers = $(this).val(); console.log("numbers", numbers);
// dump(numbers);
numbers = parseInt(numbers).toFixed(2);
console.log(numbers);
});
});
It will give you your desired output.
I wanted to know which character the user is typing into an input:
I have an input:
<input maxlength="20"/>
and a script that returns the last typed char:
var eingabe;
$('form').on('keypress', function(event) {
/// if no whitespace:
if (String.fromCharCode(event.keyCode).replace(/\s/g, "").length > 0) {
eingabe = String.fromCharCode(event.keyCode);
$('#eingabe').html("<div>Eingabe : "+ eingabe +"</div>");
}
});
My question is:
because my input has a maxlength attribute, the last typed character on the keyboard is sometimes not the last -real- typed character into the input because the input is "full". How can I get the last character typed into the input?
I haven't tried it, but it must work...
Set onkeypress= or onkeydown= on the Input element and store the key value in a LastChr variable.
I had a similar problem. I wanted to call a function if the user types a specific character into my input field. I solved it with the following:
var input = document.getElementById('myInput');
input.addEventListener('input', function() {
// Get cursor position
var start = this.selectionStart;
// Get last typed character
var lastChar = String.fromCharCode(this.value.charCodeAt(start - 1));
if(lastChar === '[YOURCHARHERE]') {
// do something
}
});
Please keep in mind, that 'input' is only supported down to IE8, but if you don't care about a proprietary browser, you should be fine. I hope this helps.
Inside your function, use the value of the input element to get the last character like $('#input_field').val().substr($('#input_field').val().length - 1) or use your best coding skill to accomplish something similar without accessing the field twice, wink wink.
Use keyup instead:
$('form').on('keyup', function(event) {
var cursorPos = event.target.selectionStart;
var lastTypedChar = elem.target.value[cursorPos - 1];
});
I am getting phone number input from user as +XXX-X-XXX-XXXX that (+XXX as country code), (X as city Code), (XXX as 1st 3 digits) and , (XXX as 2nd 4 digits). I used regular expression to confirm the entry as in following code;
function validate(form) {
var phone = form.phone.value;
var phoneRegex = /^(\+|00)\d{2,3}-\d{1,2}-\d{3}-\d{4}$/g;
//Checking 'phone' and its regular expressions
if(phone == "") {
inlineMsg('phone','<strong>Error</strong><br />You must enter phone number.',2);
return false;
}
if(!phone.match(phoneRegex)) {
inlineMsg('phone','<strong>Error</strong><br />Enter valid phone <br />+xxx-x-xxx-xxxx (or) <br />00xxx-x-xxx-xxxx.',2);
return false;
}
return true;
}
Its working very fine but the problem is that
EDIT : If the user inputs as +XXXXXXXXXXX (all together) and hit enter or go to another field, the input it self set according to the Regex that is +XXX-X-XXX-XXXX.
Can some one guide me with some example how to do this task.
Thank you
Set the element's onblur method a callback as follows:
var isValidPhoneNumber = function(string) {
...
}
var reformat = function(string) {
/*
* > reformat('example 123 1 1 2 3 123-45')
* "+123-1-123-1234"
*/
var numbers = string.match(/\d/g);
return '+' + [
numbers.slice(0,3).join(''),
numbers.slice(3,4).join(''),
numbers.slice(4,7).join(''),
numbers.slice(7,11).join('')
].join('-');
}
var reformatPhoneNumber = function() {
var inputElement = this;
var value = inputElement.value;
if (isValidPhoneNumber(value))
inputElement.value = reformat(inputElement.value);
else
// complain to user
}
Here are two example ways you could set the onblur callback handler:
document.getElementById('yourinputelement').onblur = reformatPhoneNumber;
<input ... onblur="reformatPhoneNumber"/>
You can augment reformatPhoneNumber with more validation code if you'd like, or just constantly validate the number as the user is typing it.
To only do this if your phone number is of the form +ABCDEFGHIJK, then add an string.match(/^\+\d{11}$/)!==null to your if statement. (^,$ mean the start and end of the string, \+ means a plus sign, and \d means a digit 0-9, repeated exactly {11} times). Specifically:
function isPlusAndEleventDigits(string) {
/*
* Returns whether string is exactly of the form '+00000000000'
* where 0 means any digit 0-9
*/
return string.match(/^\+\d{11}$/)!==null
}
Try shaping the input:
result = subject.replace(/^((\+|00)\d{2,3})-?(\d{1,2})-?(\d{3})-?(\d{4})$/mg, "$1-$3-$4-$5");
Then do next procedure.