Comma separated step for float number input - javascript

I want to comma seperated value for my input box. For Example 2100000.90 will be 2,100,000.90. What I achieved is 2100000.90 to 2,100,000 from some Solution in Stack overflow
<div class="input">
<label for="salary">Salary</label>
<input class='inp_cont' id="salary" name="salary" placeholder="Enter your salary" required="" type="text">
</div>
And My Javascript is
document.getElementById('salary').addEventListener('input', event =>
event.target.value = (parseInt(event.target.value.replace(/[^\d]+/gi, '')) || 0).toLocaleString('en-US')
);
I want both comma separated and value after point.
Thanks in advance

Your logic is defeated by its own.
Here is what you are currently doing:
ask the user to input a series of digits and only digits
parse the input into an integer
format the integer in the en-US locale
what will happen when the user tries to input a decimal point?
It will automatically be removed by the regex replace.
What you need to do is the following:
Allow the user to input digits and decimal points
That will mess up if the user types more than one decimal point, but that can be detected and dealt with later
Try to detect if the input is a valid number or not
if not, then provide a negative feedback to the user
if yes, then provide a positive feedback
most important: the process of converting text to number will get rid of the decimal point if it is the last character in the input box. The user will not see the dot since the conversion from text to number will see that it is the last thing and it's not affecting the number, so it is removed, and the user doesn't know why.
Therefor, it is essential to add the "dot" back if it is the last thing typed by the user.
document.getElementById('salary').addEventListener('input', event => {
event.preventDefault();
// allow only digits and dots
let text = event.target.value.replace(/[^\d\.]/gi, '');
// check if last character is a dot
let lastCharIsAdot = text.substr(text.length - 1, 1) === ".";
// try to check if input text is a valid number
if (isNaN(text)) {
// if not, then give feedback to the user
event.target.classList.remove('valid');
event.target.classList.add('invalid');
} else {
// if yes, then give positive feedback
event.target.classList.remove('invalid');
event.target.classList.add('valid');
// format number
event.target.value = Number(text).toLocaleString("en-US");
// this will remove the dot if it is the last thing input
// therefor, we need to put it back
if (lastCharIsAdot) event.target.value += ".";
}
});
.valid {
background-color: lightgreen;
color: darkgreen;
}
.invalid {
background-color: pink;
color: maroon;
}
<div class="input">
<label for="salary">Salary</label>
<input class='inp_cont' id="salary" name="salary" placeholder="Enter your salary" required="" type="text">
</div>

You can try this
parseInt(number, 10).toLocaleString()
here is also the link from mozilla docs about Number.prototype.toLocaleString() method. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString

This function help you :
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
Output :
numberWithCommas(88888888.88)); // 88,888,888.88

Related

Client side input validation via Bootstrap and jQuery

I am kind of stuck, with this I don't even know where to start but
I need to mark the first input as green on the correct password, red if the password does not meet the requirements
Requirements:
Passwords must be at least 10 characters long and have lowercase and uppercase letters
Passwords less than 15 characters must have a number and a special character
Marking the second input outline as green if it matches the first input and the password is correct, red otherwise.
Any help would be very appriciated
<div class="form-group">
<label for="newPasswordTextBox">Password</label>
<input type="password" id="newPasswordTextBox" class="form-control" name="newPassword"
placeholder="New Password" autocomplete="off">
</div>
<div class="form-group">
<label for="confirmNewPasswordTextBox">Confirm Password</label>
<input type="password" id="confirmNewPasswordTextBox" class="form-control"
name="confirmNewPassword" placeholder="Confirm New Password" autocomplete="off">
</div>
<div class="small">
<ul>
<li>Passwords must be at least 10 characters long and have a lowercase and
uppercase letters</li>
<li>Passwords less than 15 characters must have a number and a special
character</li>
</ul>
</div>
You could try using javascript to collect both inputs document.getElementById("newPasswordTextBox") and document.getElementById("confirmNewPasswordTextBox") and then you can take the .value attributes from the input boxes to check the input against if conditionals with your specified requirements. eg.
let newPass=document.getElementById("newPasswordTextBox");
newPass.addEventListener("keyup",function(evt){
let val=newPass.value;
//check requirements here
});
or in jquery
$("#newPasswordTextBox").on("keyup", function(evt){
let val=$("#newPasswordTextBox").val(); //get the value using jquery
//check requirements here
});
Next, use if conditionals by //check requirements here to get your functionality. You can use val.length to get the length of the string obtained from the textbox, then just compare this to the size you want(10). Repeat the aforementioned for 15 but just add the extra requirements of checking for numbers and special characters(see regular expressions in javascript). For validating that passwords match just grab both values and use "===" to determine if they are equal. You can also change the input boxes' outline colours using the border property as follows:
$("#newPasswordTextBox").css({"border-color":"green"});//Use the appropriate id and colour for the box you wish to change
Addition(correcting the authors code post):
I've managed to capture most of what I believe you'd want here and corrected some of your code by changing the wrong variables that were called and changed to the proper regex code.
$("#newPasswordTextBox").on("keyup", function () {
let pass = $("#newPasswordTextBox").val();
if ((pass.length >=10) && (pass.length < 15)) {
var regex = /^(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[ `!##$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~])/;
if(!pass.match(regex)){
$("#newPasswordTextBox").css({ "border-color": "red"});
}
else{
$("#newPasswordTextBox").css({ "border-color": "green" });
}
} else if (pass.length>=15){
$("#newPasswordTextBox").css({ "border-color": "green","outline":"none" });
}else {
$("#newPasswordTextBox").css({ "border-color": "red","outline":"none" });
}
}
);
$("#confirmNewPasswordTextBox").on("keyup", function () {
let pass = $("#confirmNewPasswordTextBox").val();
let confpass = $("#newPasswordTextBox").val();
if (pass === confpass) {
$("#confirmNewPasswordTextBox").css({ "border-color": "green","outline":"none" })
} else {
$("#confirmNewPasswordTextBox").css({ "border-color": "red","outline":"none" });
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<body>
<input type="text" id="newPasswordTextBox" placeholder="new">
<input type="text" id="confirmNewPasswordTextBox" placeholder="re-enter">
</body>

format numbers of RUT with simple javascript or jquery

I have a form where chilean customers need to write their security number ( RUT )
the format can be with 1.234.567-8 for old people or 12.345.678-9 for younger people
What I need is that when they type down their number the input text change as soon as they type down and start formatting the number with the two dots and - like in the example above
I created this code
<input type="text" class="inputs" name="cliente" id="cliente"
onkeydown = "this.value = this.value.replace( /^(\d{1})(\d{3})(\d{3})(\w{1})$/, '$1.$2.$3-$4')" >
It works almost good but only with 9 digits RUTs but not with 8 digits RUTs, any idea how to accomplish this ?
This logic removes any - or . you previously put in it, or the user put in it, and then performs the reformatting. It also fires on keyup rather than keydown as the new value would not have been added yet on the keydown.
function formatCliente (cliente) {
cliente.value = cliente.value
.replace(/[^0-9]/g, '')
.replace( /^(\d{1,2})(\d{3})(\d{3})(\w{1})$/, '$1.$2.$3-$4')
}
<input type="text" class="inputs" name="cliente"
id="cliente" onkeyup="formatCliente(this)">
i've made an correction to accept a RUT that's end with letter (like 8.345.434-k or 20.432.345-k)
function formatCliente (cliente) {
cliente.value = cliente.value
.replace(/[^0-9\dkK]/g, '')
.replace( /^(\d{1,2})(\d{3})(\d{3})(\w{1})$/, '$1.$2.$3-$4')
}

Aadhar Number Format Validation for HTML Textbox

I want aadhar number in format of xxxx-xxxx-xxxx. Text box sholud take the input in this format automatically.
While entering the input the input should automatically convert into this(xxxx-xxxx-xxxx) format.
Only numericals should be accepted.
I want mobile number in format +91(or any other country code)-9999999999(10 digit mobile number).
I have tried /^(?:\(\d{3}\)|\d{3}-)\d{3}-\d{4}$/, but its not working please help
I want aadhar number in format of xxxx-xxxx-xxxx. text box sholud take
the input in this format automatically.
One example would be to enforce input to only accept the adhaar number format
$('[data-type="adhaar-number"]').keyup(function() {
var value = $(this).val();
value = value.replace(/\D/g, "").split(/(?:([\d]{4}))/g).filter(s => s.length > 0).join("-");
$(this).val(value);
});
$('[data-type="adhaar-number"]').on("change, blur", function() {
var value = $(this).val();
var maxLength = $(this).attr("maxLength");
if (value.length != maxLength) {
$(this).addClass("highlight-error");
} else {
$(this).removeClass("highlight-error");
}
});
.highlight-error {
border-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" data-type="adhaar-number" maxLength="19">
I am not interested in giving u everything, but I will point you in the right direction. Use regular expressions.
This regex will help your case but you need to put in your effort on how it must be used in your situation.
console.log(/\d{4}-\d{4}-\d{4}-\d{4}/.test('1000-1000-1000-1002'));

Password box - get value from input field with javascript

Does anybody know how to make a password box like this image?
This password box will be the first page of the site/mobile. The user have to insert 4 numbers (1 - 2 - 3 - 4). If they dont type 1 -2 - 3 - 4 as their password, they will get a message box saying "wrong password". If they type correct they will be sent to the next page.
Appreciate help!
Here a working sample
var password = [1,2,3,4];
var pwdInputs = $("#pwdContainer input");
var inputs = pwdInputs.toArray();
pwdInputs.keyup(function(){
if (this.value.length == this.maxLength) {
if(inputs.indexOf(this) == inputs.length-1){
testPassword();
} else {
$(this).next('input').focus();
}
}
});
function testPassword(){
var valid = true;
for(var i=0; i<inputs.length; i++){
if(password[i] != inputs[i].value){
valid = false;
break;
}
}
if(valid){
console.log("Correct Password!");
window.location.href = 'http://www.google.com';
}else{
console.log("Wrong Password!");
}
}
div.box-big {
background-color: grey;
margin: auto;
display:inline-block;
padding: 10px;
padding-top: 20px;
}
input.box-text {
width: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="pwdContainer" class="box-big" >
<input type="text" maxlength="1" class="box-text" >
<input type="text" maxlength="1" class="box-text">
<input type="text" maxlength="1" class="box-text">
<input type="text" maxlength="1" class="box-text">
</div>
As per your comment, in the picture provided you seem to want to provide the user with 4 boxes, and in it, they would then type their password.
In this case, I do not think that you need regular expressions at all. What you need to do, in my opinion, is the following:
Create the 4 password field text boxes.
In the section where you check the password, simply check that the first box has a value of 1 stored in it, the second box has 2, the third has 3 and the fourth has 4.
Since you are looking for specific, entire string values, as opposed to patterns, regular expressions are not needed.
You probably want a regular expression (regex), which can be used to validate your input.
The regex string would look something like this: \d{4} or [0-9]{4}, which is basically saying match all digits (`\d' or numbers from 0-9) four times strictly, so only four digits exactly would be valid
<input type="password" pattern="[0-9]{4}" id="passcode" required onkeyup="checkIfValid()">
<p id="isValid"></p>

In JavaScript, how do I detect whether or not the input contains letters?

My code is below, it outputs what the user is typing in the text box. It should output an error message if the user puts anything other than a number. I'm confused as to how to do this, though. Quite frankly, I'd settle with it being able to detect whether or not the first letter of input is a B, but I can't quite figure that out either and the former option is preferred.
HTML
<label for="bannerID">Banner ID: B</label><input type="text" name="bannerID" id="bannerID" onkeyup="showBannerID()" value="" /><br />
<p id="bannerOutput"></p>
JavaScript
function showBannerID() {
var textInput = document.getElementById('bannerID').value;
if (textInput.length == 0) {
document.getElementById('bannerOutput').innerHTML = "<strong class=\"error\">Field can't be empty!</strong>";
}
else if (textInput.charAt(0) == "B") {
document.getElementById('bannerOutput').innerHTML = "<strong class=\"error\">Please omit the B! It's not necessary.</strong>
}
else {
document.getElementById('bannerOutput').innerHTML = "Your Banner ID is: <strong>B" + textInput + "</strong>.";
}
}
You can use regular expressions to search for anything other than numbers:
if (/[^\d]/.test(textInput)) {
/* error stuff */
}
You can use isNaN() (Not a Number) as a condition.
isNaN(123) would give false, isNaN("hello") would give true.

Categories