Prevent inputting leading 0 - javascript

I can input
0 but not 0123. How do I prevent users not to input 0 at the first position of the input text field?

Let them input it, just trim it when focus changes:
inputElement.onblur = function() {
this.value = this.value.replace(/^0+(?=\d)/,'');
}
Fiddle
Note that it's specifically looking for a digit (\d) after the 0's that it's nuking, so it won't touch the zero in something like 0.123. If you want to get rid of those, too, just change the \d to ., which matches any character whatsoever.

One way to do this is to check the first character in the input using charAt().
Demo
JS:
function check(){
var number = document.getElementById('input').value;
if(number.charAt(0) === 0)
alert('Leading zero in the input.')
else
alert('No leading zero in the input.')
}
EASIER SOLUTION:
For the input, just check the first character like an array:
if(number[0] === '0')
// do something
Demo

Related

regex: remove leading zeros, but keep single zero

I have an input field to which I have tied a formatting function that is triggered whenever the field loses focus.
What I aim to achieve is that I remove all the leading zeros from an input and I did achieve that with the below line. However, when the user wants to enter a single 0 or something like 0000 I still want that field to end with the value 0 (single). With .replace(/^0+/, '') it would remove every zero and return just an empty string. Someone knows what regex could handle this?
const formatNumber = ($field) => {
var number = $field.val().replace(/\./g, '').replace(/\s/g, '').replace(/^0+/, '');
return number;
};
note: if(number === "") number = "0" is not an option.
edit1:: I noticed there seems to be a bit of confusion. e.g "0009825" need to become 9825 and not 09825. the only instance where i want a 0 up front is when the value is simply zero.
You ay use this regex replacement:
.replace(/^(?:0+(?=[1-9])|0+(?=0$))/mg, '')
RegEx Demo
RegEx Details:
^: Start
(?:: Start capture group
0+(?=[1-9]): Match 1 or more zeroes that must be followed by 1-9
|: OR
0+(?=0$): Match 1 or more zeroes that must be followed by one 0 and end
): End capture group
Replacement is empty string which will leave a single 0 if there are only zeroes in string otherwise will remove leading zeroes.
Alternative solution using a capture group:
str = str.replace(/^0+(0$|[1-9])/mg, '$1');
A simple reg exp with leading zeros and match one digit in a capture group
const cleanZeros = str => str.replace(/^0+(\d)/, '$1')
var tests = ["0009876","0", "0000", "9999", "0090000"]
tests.forEach( s => console.log(s, cleanZeros(s)))

Regex to check only numbers(negative and positive)

There is an input field on the JSP where users can enter numbers(negative and positive both).
I've a JS function that checks on each key up event on the input field is not a number, it should replace it with blank.
var txt = $(elem).val();
if(!(txt.match(/^-?[0-9]*$/))) {
$(elem).val(txt.replace(/^-?[0-9]+/g, ''));
}
My if condition is working fine, but I'm not able to create a regex for replacing.
Edit: question was clarified that only numeric values should be accepted
You could just check that the number is < 0 after removing all non-numeric characters:
// remove all non-numeric characters
var txt = $(elem).val().replace(/[^\-0-9]/g, '');
if(parseInt(txt) < 0)){
// negative number
}
To check if a number do this
var txt = $(elem).val();
if (!isNAN(txt) && parseInt(txt) >=0) {
//validate
} else {
// Invalidate
}

Javascript Regular Expression to add dash after every 3rd and 4th characters

The following regex:
x.toString().replace(/\B(?=(?:\d{3})+(?!\d))/g, "-");
adds dash after each 3rd character so entered 123456789 turns into 123-456-789.
Im trying to use this regex to format phone number. The problem arises on the 10th character. So entered 1234567890 turns into 1-234-567-890.
How would I modify the above regex to turn strings that have 10 digits into 123-456-7890. I use this regex because this happens as user is typing in uses keyup event.
If you know easier or better way of doing this please help me out, dashes has to be added while user is typing in. No other characters allowed.
Notes:
Cant use Jquery Masked input plugin (because if editing the middle character it's focus gets messed up)
How about
> "12345678".match(/\d{3}(?=\d{2,3})|\d+/g).join("-")
"123-456-78"
> "123456789".match(/\d{3}(?=\d{2,3})|\d+/g).join("-")
"123-456-789"
> "1234567890".match(/\d{3}(?=\d{2,3})|\d+/g).join("-")
"123-456-7890"
If you ALREADY have the complete number or string
var x = "329193914";
console.log(x.replace(/(\d{3})(\d{3})(\d{3})/, "$1-$2-$3"));
If you WANT AS someone is typing...
$('#locAcct').keyup(function () {
var foo = $(this).val().split("-").join(""); // remove hyphens
if (foo.length > 0) {
foo = foo.match(new RegExp('.{1,3}', 'g')).join("-");
}
$(this).val(foo);
});
Do you need to use regular expressions for everything or would maybe something like this also help you out?
function convertToValidPhoneNumber(text) {
var result = [];
text = text.replace(/[^\d]/g,"");
while (text.length >= 6) {
result.push(text.substring(0, 3));
text = text.substring(3);
}
if(text.length > 0) result.push(text);
return result.join("-");
}
You could use this function everytime the text in your inputfield changes. It will produce the following results:
"12345678" -> "123-45678"
"123d456789" -> "123-456-789"
"123-4567-89" -> "123-456-789"
I believe the simplest way would be to add dash after every n digits would be like
var a = $('#result');
var x = "<p>asiija kasdjflaksd jflka asdkhflakjshdfk jasd flaksjdhfklasd f</p><p>12345678912345678912345678912312344545545456789</p>"
a.html(x.replace(/(\d{15})/g, "$1-"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="result"></div>
Most easiest way is the following using simple javascript onkey and function... it will put dash hyphen after every 3 characters you input / type.
<input type="text" class="form-control" name="sector" id="sector" onkeyup="addDash(this)" required>
add the following script
<script>
function addDash (element) {
let ele = document.getElementById(element.id);
ele = ele.value.split('-').join(''); // Remove dash (-) if mistakenly entered.
let finalVal = ele.match(/.{1,3}/g).join('-');
document.getElementById(element.id).value = finalVal;
}
</script>

alphanumeric regex javascript

I am having a problem to get the simple reges for alphanumeric chars only work in javascript :
var validateCustomArea = function () {
cString = customArea.val();
var patt=/[0-9a-zA-Z]/;
if(patt.test(cString)){
console.log("valid");
}else{
console.log("invalid");
}
}
I am checking the text field value after keyup events from jquery but the results are not expected, I only want alphanumeric charachters to be in the string
This regex:
/[0-9a-zA-Z]/
will match any string that contains at least one alphanumeric character. I think you're looking for this:
/^[0-9a-zA-Z]+$/
/^[0-9a-zA-Z]*$/ /* If you want to allow "empty" through */
Or possibly this:
var string = $.trim(customArea.val());
var patt = /[^0-9a-z]/i;
if(patt.test(string))
console.log('invalid');
else
console.log('valid');
Your function only checks one character (/[0-9a-zA-Z]/ means one character within any of the ranges 0-9, a-z, or A-Z), but reads in the whole input field text. You would need to either loop this or check all characters in the string by saying something like /^[0-9a-zA-Z]*$/. I suggest the latter.
I fixed it this way
var validateCustomArea = function () {
cString = customArea.val();
console.log(cString)
var patt=/[^0-9a-zA-Z]/
if(!cString.match(patt)){
console.log("valid");
}else{
console.log("invalid");
}
}
I needed to negate the regex

Input a comma after every 10 digit in Javascript?

I put 10 digit mobile numbers in a Textarea like the follwoing.
242452354643663463636346366363463636365636363634656346
but i need to put comma(,) after every 10 digit number.
Like this?
"242452354643663463636346366363463636365636363634656346".replace(/(\d{10})/g,"$1,")
// 2424523546,4366346363,6346366363,4636363656,3636363465,6346
Above solution did not help with splitting a 10 digit phone number being typed into for example a textarea.
My solution: 1. your text area should be validated to return only numbers onKeyPress.
then
function commafyPhone(str){
var newStr='';
if(str.length>10){
var str_array=str.split(",");
for(var i = 0; i < str_array.length; i++) {
newStr+=str_array[i].replace(/(\d{10})/g,'$1,');
}
return newStr;
}
return str;
}
On the textarea form field, i used:
onKeyUp="this.value=commafyPhone(this.value);"
However, my solution requires to remove the comma on your last number entered.

Categories