I have an input for a phone number in french format
The input accepts two kinds of format, so i can input this:
0699999999
+33699999999
no check is done for the length of the number.
The table in database, the field is of varchar 12, i can have shorter input though.
The constraints: input contains only digits from 0 to 9, optional '+' sign accepted only if it starts the string, not after.
Currently i am in Angular with a directive, in that directive the heart is this expression :
var transformedInput = inputValue.replace(/[^0-9]/g, '');
i want the optional leading '+' sign, how can i achieve this?
thanks.
You could make the plus sign optional:
if (/\+?\d*/.test(subject)) {
// Successful match
} else {
// Match attempt failed
}
subject is the text you want to check. \+ makes the plus sign a literal and the questionmark makes it optional.
If you just want to check wether ther is a plussign drop the questionmark. But if that is your goal don't use a regex. That is too much overhead. Simply get the first charactor of the trimmed string and check for the plus.
Change it to
var transformedInput = inputValue.replace(/[^0-9\+]/g, '').replace(/(.)\+/g, '$1');
Note - this will NOT add a + unless there is already a + in the input
What it does is
Do not remove the + symbol on the first replace
Remove every + symbol that is preceded by some character on the 2nd replace
Related
I am creating an input box with an onChange function that will check to see if the characters are only digits and only allow up to one period/dot '.'
The function I have here is not working:
function addPercentSeparator(n) {
let str = n;
let match = str.match(/\d*\.\d*/)
if (match) {
return str;
}
}
I also tried: let match = str.match(/^([0-9]+(\.[0-9]+)?)/)
What I am trying to achieve is only allowing for one period.
If the user enters a number without a period, it will append a period to end of string when they click outside the input box.
This regex is supposed to do the trick:
^\d*\.?\d*$
But if you'll ask me, I would make sure there are digits before the dot, using ^\d+\.?\d*$.
Explanation:
As the dot isn't mandatory, I've added the ?, which symbolizes "0 or 1 occurrences".
I've also added the ^ and the $ to make sure no parts of the string will be matched if the whole string is illegal.
I hope this works for you!
$('#target').val($('#target').val().replace(/[^\d]/g, ""));
I use the above code to leave only numeric characters in an input value I would also like to allow '+' and '-'.
How would I modify the regex to allow this?
Help much appreciated
Put - and + in the character class.
$('#target').val($('#target').val().replace(/[^-+\d]/g, ""));
FWIW I use a couple of input classes that I control with jQuery:
<input class="intgr">
<input class="nmbr">
$("input.intgr").keyup(function (e) { // Filter non-digits from input value.
if (/\D/g.test($(this).val())) $(this).val($(this).val().replace(/\D/g, ''));
});
$("input.nmbr").keyup(function (e) { // Filter non-numeric from input value.
var tVal=$(this).val();
if (tVal!="" && isNaN(tVal)){
tVal=(tVal.substr(0,1).replace(/[^0-9+\.\-]/, '')+tVal.substr(1).replace(/[^0-9\.]/, ''));
var raVal=tVal.split(".")
if(raVal.length>2)
tVal=raVal[0]+"."+raVal.slice(1).join("");
$(this).val(tVal);
}
});
intgr strips all non-numeric
nmbr accepts +, -, . and 0-9. The rest of the string gets stripped of all but 0-9 and the first . If you are OK with the + and - being anywhere, Bamar's solution is perfect, short and sweet. I needed the +/- to be only in the first character position if at all, and only one . (i.e. strip out beyond the first period so 2.5.9 would be 2.59)
I have a text box and it says "Phone:" as the standard here for phone number is (XXX)-XXX-XXXX
I'd like to have a javascript that automatically puts my numbers into that format if it's not in that format, so if you typed 9993334444 then it would change it automatically on the fly as I'm typing to (999)-333-4444 I have looked around Google for Javascript Phone Regex to no success, maybe a Regex isn't what I'm looking for?
you want to add an onkeyup event with a regex like
this.value = this.value.replace(/^\(?([0-9][0-9][0-9]){1}\)?-?([0-9][0-9][0-9][0-9]){1}-?([0-9][0-9][0-9]){1}$/, '($1)-$2-$3');
Check out http://jsfiddle.net/R8enX/
/ means start/end a regex string
^ means start of matching string
$ means end of matching string
? means 0 or 1 instances (make braces and dashes optional)
[0-9] means any single digit
(x){1} tags x as an expression that we can reference in the replacement with a $ sign
EDIT: realized I missed a digit on the last group of numbers, the jsfiddle will only work (properly) with 3 digits in the last group
To build somewhat on #Andrews answer you can check for a valid (local)phone number via this method. If the number is shorter or larger than 10 digits, it collapses back into an invalid number
-
<input type="text" onBlur="localNumber(this.value)"/>
<div id="output"></div>
-
<script>
var localNumber = function(str){
repl = str.replace(/^([0-9]{3})([0-9]{3})([0-9]{4})$/, "($1)-$2-$3");
outp = document.getElementById('output');
if( repl.match(/\W/) )
{
outp.innerHTML = repl;
}
else
{
outp.innerHTML = 'Invalid number for this region';
}
}
</script>
I have a page with some elements that are controlled by the user. One of these is a text input field, where the user is supposed to input a number. Everything works well if the user only inputs digits (EG 9000), but is the user uses comma notation (the being 9,000) javascript doesn't take the input as an integer.
How can I remove the commas and/or force the input to an integer? I tried using parseint(), but it doesn't seem to work with commas.
Use a global regular expression to replace all commas with an empty string:
var str = "12,345,678";
str = str.replace(/,/g, "");
parseInt(str, 10);
or even better
var s="jdjsghd0182.99";
var str = parseFloat(s.replace(/[^0-9 | ^.]/g, ''));
Or even better, given the general unreliability of user input, use this to get rid of all non-numeric characters:
var s = "9,Ljk876";
var t = parseInt(s.replace(/[^0-9]/g, ''));
alert ("s:" + s + ", t:" + t);
maybe
parseint(ny9000withCommas.replace(/\,/g,""))
lets talk about the restriction :
you can/should allow the user to enter both 9000 & 9,000
you can check validy via REGEX.
in the server side - you should eleminate the commas and treat it as integer.
Firstly apologies for being a tad dim. I need to create a test to check the if the value of an input field.
I currently use /[^A-Za-z0-9 ]/.test(document.form.Serial.value) to test to see if the value of Serial is alphanumeric only.
Now, if an additional field is set, Serial must either being with 'i' or 'I', then the remaining characters must all be numbers. I had considered doing this with substrings, but it seems a bit long and unnecessary.
Any advice people can give would be very much appreciated!
If you want to test if a string begins with i or I, and then only contain numbers, you could use a regular expression such as this one :
/^[iI][0-9]+$/
Or, for a case-insensitive match :
/^i[0-9]+$/i
Basically, this will match :
Beginning of string : ^
an i
any character between 0 and 9 : [0-9]
one or more time : [0-9]+
end of string : $
You may try the code below
var test_value = false
if (document.form.Additional_Field.value) {
test_value = /^(i|I)[0-9]+/.test(document.form.Serial.value) }
else {
test_value = /[A-Za-z0-9]+/.test(document.form.Serial.value) }
it will result in test_value set to true if Serial is either alphanumeric or if Additional_Field has value true and Serial begins with i or I fallowed by any number of numbers, and test_value set to false otherwise.
Why not break the problem down. You have two valid inputs, so a pattern for syntactically checking the input would be:
/^([iI][0-9]+)|([A-Za-z0-9]+)$/
Then you have a separate, and simpler, problem of determining whether the validated input is appropriate based on the state of the other controls on the form.