Provide hyphens between numbers as a formatting in Javascript - javascript

So I have a requirement to format a 9 digit number by providing hyphens in the appropriate places.If the number is 123456789 ,after formatting it has to be 123-45-6789.To achieve this,I have set the maxlength as 9 in HTML
<div class="form-group">
<label class="col-sm-2 control-label labelfont">SSN:</label>
<div class="col-sm-6">
<input type="text" class="form-control" placeholder="Enter the SSN" id="SSN" name="SSN" data-bind="value: SSN" onkeypress="return onlyNumbers(event);" maxlength="9">
</div>
<label class="col-sm-4 labelfont errorMsg" id="Err_SSN">Enter the SSN</label>
</div>
and in the JS,Ihave the following code
var Provider = function () {
var self = this;
self.ProviderID = ko.observable("");
self.SSN = ko.observable("");
};
var blurred = false; //Prevent reformatting when Tab back in.
$("#SSN").blur(function () {
if ($(this).val().trim().length == 0) {
$("#Err_SSN").text("Enter the SSN");
$("#Err_SSN").show();
$(this).addClass('borderclass');
}
else {
if (!blurred) {
$("#Err_SSN").hide();
var SSN = $("#SSN").val();
$("#SSN").val(SSN.substring(0, 3) + "-" + SSN.substring(3, 5) + "-" + SSN.substring(5));
$("#SSN").removeClass('borderclass');
Provider.SSN($("#SSN").val());
blurred = true;
}
}
});
$(document).ready(function () {
ko.applyBindings(new Provider());
});
The above code works when I tab out after entering 9 digits in the relevant field,but as you may have already figured out,it does not work if I tab back in to edit the data.Now,I know the edit is not happening because the max length is 9 and hyphen is seen as one of the characters.But if I allow more than 9 digits in the field,the number could be considered as invalid.So,if you folks have a better way of achieving my requirement,please guide me.

You could remove the hyphen(s) when focusing back on the text field:
$("#SSN").focus(function(){
$(this).val() = $(this).val().replace(/-/g,"");
});
Not tested, but that's the idea.

Related

Validating and formatting for SSN field with hyphens: 123-45-6789

I am currently working on a simple form to practice Javascript validation and am having difficulty in adding the dashes in-between the numbers (like this: 123-45-6789). I need to keep the validation that displays whether or not it is valid (9 digits only) as the user is typing. This is what I have so far
function ssnFunction()
{
let x = document.getElementById("ssn").value;
let text;
if (isNaN(x) || x.toString().length != 9)
{
text = "\tMust be 9 digits";
ssnValidation = 0;
}
else
{
text = "Valid";
ssnValidation = 1;
}
document.getElementById("ssnvalid").innerHTML = text;
return ssnValidation;
}
<label for="ssn">Social Security: </label>
<input type="text"
name="ssn"
id="ssn"
value=""
required="required"
onkeyup="ssnFunction()" size="20" />
<span id="ssnvalid"></span>
Any help and explanation is greatly appreciated

limit text input to match HH:MM format with max hours and resetting to previous value if entered wrong

I want to limit value/numbers inside a text input to match the HH:MM format, possibly also limit max hrs input (i.e. max 8) while also preventing any other input format in that field. Ideally would be if a number is entered to high, instead of resetting the field/number set it back to the previous number that was already contained or selected via the range slider (not simply clearing it).
Would I have to extract the first, second, fourth & fifth number from that text field and check them individually or any other approach I could use?
The only other alternative I can think of is using two separate text input fields and display a static colon symbol between them, checking each individually (but entry field may look neater where only hrs and mins are changeable) i.e.
document.getElementById('hrs').addEventListener('keyup', function(){
this.value = (parseInt(this.value) < 0 || parseInt(this.value) > 8 || isNaN(this.value)) ? "00" : (this.value)
});
document.getElementById('mins').addEventListener('keyup', function(){
this.value = (parseInt(this.value) < 0 || parseInt(this.value) > 8 || isNaN(this.value)) ? "00" : (this.value)
});
//still requires a reset to previous value instead of fixed "00"
//I also tried this with just one field but no idea how to target just the first and last double digits separately while ignoring the colon symbol.
Here is my HH:MM range slider with synced text input field to allow for either input (I haven't found yet any better alternative to this).
HTML
<script
src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"
integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ=="
crossorigin="anonymous"
referrerpolicy="no-referrer"
></script>
<div class="slidecontainer">
<input type="text" id="durationtimestamp" value="00:00" oninput="durationtimestamp(this.value)" required="required">
<input type="range" min="0" max="480" value="0" class="durationslider" id="durationrange" oninput="durationslider(this.value)">
</div>
JS
function durationslider(value) {
var hours = Math.floor(value / 60).toLocaleString('en-US', {
minimumIntegerDigits: 2,
//useGrouping: false
});
var minutes = (value % 60).toLocaleString('en-US', {
minimumIntegerDigits: 2,
//useGrouping: false
});
duration = hours+':'+minutes;
document.getElementById("durationtimestamp").value = duration;
}
function durationtimestamp(value) {
var hours = Math.floor(value / 60).toLocaleString('en-US', {
minimumIntegerDigits: 2,
//useGrouping: false
});
var minutes = (value % 60).toLocaleString('en-US', {
minimumIntegerDigits: 2,
//useGrouping: false
});
var myduration = moment.duration(value).asMinutes().toString();
var current = document.getElementById("durationrange").value;
document.getElementById("durationrange").value = myduration;
}
Demo: https://jsfiddle.net/markusd1984/u3gfod5x/11/
You can check the input with js like this
const input = document.querySelector("input");
const checkingInput = (event) => {
console.log(event.target.value.length <= 5);
if(!/0[0-8]:[0-5][0-9]$/.test(event.target.value)){
input.value = null;
}
}
<input type="text" onchange="checkingInput(event)"/>
it should work 🤔
You can also use the pattern attribute or a <datalist>.
Although you didn't mention them a <select> or some radio buttons could also be used.
const error = document.getElementById("error");
document.getElementById("frm").addEventListener("change", function(e) {
const valid = this.checkValidity();
error.classList.toggle("hidden", valid);
if (!valid) {
const value = this.getAttribute("value");
this.value = value;
}
});
.hidden {
display: none;
}
.error {
color: red;
}
<span id="error" class="error hidden">Error</span>
<form id="frm">
<label for="time">Time</label>
<input type="text" id="time" pattern="[0]?[0-8]:[0-5][0-9]" placeholder="HH:MM" value="1:00" required>
<br>
<label for="duration">Time</label>
<input list="duration-options" id="duration" pattern="[0]?[0-8]:[0-5][0-9]" placeholder="HH:MM" value="1:00" required>
<datalist id="duration-options">
<option>0:30</option>
<option>1:00</option>
<option>4:00</option>
<option>8:00</option>
</datalist>
<br>
<label for="times">Time</label>
<select id="times">
<option>0:30</option>
<option>1:00</option>
<option>4:00</option>
<option>8:00</option>
</select>
<p>Time</p>
<label><input type="radio" name="time" value="0:30">0:30</label>
<label><input type="radio" name="time" value="1:00">1:00</label>
<label><input type="radio" name="time" value="4:00">4:00</label>
<label><input type="radio" name="time" value="8:00">8:00</label>
</form>

How to input phone no in this 'xxx-xxx-xxxx' format in number input field

I want that whenever I type a number in the number input field in XXXXXXXXXX format it takes as XXX-XXX-XXXX using HTML, CSS and javascript.
Just like this snippet but without using the mask script.
$('.phone_us').mask('000-000-0000');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://igorescobar.github.io/jQuery-Mask-Plugin/js/jquery.mask.min.js" type="text/javascript"></script>
<!--mask script-->
<input type="text" class="phone_us" />
There are some working answers here, but this solution is more stable.
Using the oninput event for instant replace and ...
Applying regex on the full string, to allow copy/paste, and finally ...
This code is shorter as well:
$('.phone_us').on('input', function() { //Using input event for instant effect
let text=$(this).val() //Get the value
text=text.replace(/\D/g,'') //Remove illegal characters
if(text.length>3) text=text.replace(/.{3}/,'$&-') //Add hyphen at pos.4
if(text.length>7) text=text.replace(/.{7}/,'$&-') //Add hyphen at pos.8
$(this).val(text); //Set the new text
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="phone_us" maxlength="12">
Or even without jQuery:
document.querySelector('.phone_us').addEventListener('input', function() { //Using input event for instant effect
let text=this.value //Get the value
text=text.replace(/\D/g,'') //Remove illegal characters
if(text.length>3) text=text.replace(/.{3}/,'$&-') //Add hyphen at pos.4
if(text.length>7) text=text.replace(/.{7}/,'$&-') //Add hyphen at pos.8
this.value=text; //Set the new text
});
<input class="phone_us" maxlength="12">
you could try like this
$(document).ready(function () {
$(".phone_us").keyup(function (e) {
var value = $(".phone_us").val();
if (e.key.match(/[0-9]/) == null) {
value = value.replace(e.key, "");
$(".phone_us").val(value);
return;
}
if (value.length == 3) {
$(".phone_us").val(value + "-")
}
if (value.length == 7) {
$(".phone_us").val(value + "-")
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://igorescobar.github.io/jQuery-Mask-Plugin/js/jquery.mask.min.js" type="text/javascript"></script>
<!--mask script-->
<form id="form1" runat="server">
<input type="text" maxlength="12" class="phone_us"/>
</form>
You can implement like this
document.getElementById('txtphone').addEventListener('blur', function (e) {
var x = e.target.value.replace(/\D/g, '').match(/(\d{3})(\d{3})(\d{4})/);
e.target.value = '(' + x[1] + ') ' + x[2] + '-' + x[3];
});txtphone
<input type="text" class="phone_us" id="txtphone" placeholder = "(000) 000-0000"/>
<input type="tel" id="phone" name="phone"
pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}"
required>
Use HTML5 input type=tel to get phone number, and pattern attribute to specify any pattern.
[0-9]{3} represent the 0-9 numeric and 3 digits.
Then, add a hyphen (-), and use the numerics pattern again.
You can use own pattern and your country wise pattern like
[1-9]{4}-[1-9]{6} for the format 1234-567890.
Use the min-length and max-length in HTML5 to set limit.
Note that these patterns won't automatically add the hyphens, but will only allow correctly formatted input.
If you want get more patterns, search on web or see HTML5pattern.com
Pure javascript.
Enter 10 digits in the input field and click anywhere outside the input field.
var myTel = document.getElementById("tel");
myTel.addEventListener("blur", function() {
var str=myTel.value;
var pattern=/[0-9]{10}/;
if (pattern.test(str)) {
newstr=str.slice(0,3)+'-'+str.slice(3,6)+'-'+str.slice(6,10);
myTel.value=newstr;
}
else {
// bad
myTel.value='bad value: only 10 digits';
}
})
<form>
<input type="text" id="tel" name="tel" maxlength='10'>
</form>

JavaScript to only allow numbers and certain length and no periods

I need help with a piece of JavaScript. I have this code:
<script>
function FilterInput(event) {
var keyCode = ('which' in event) ? event.which : event.keyCode;
isNotWanted = (keyCode == 69);
return !isNotWanted;
};
function handlePaste(e) {
var clipboardData, pastedData;
clipboardData = e.clipboardData || window.clipboardData;
pastedData = clipboardData.getData('Text').toUpperCase();
if (pastedData.indexOf('E') > -1) {
e.stopPropagation();
e.preventDefault();
}
};
</script>
I would like to limit the user's input to only 5 digits. For example, for this entry box, I'd like no more than five numbers to be allowed (12345 for example) and no periods:
<div class="col-md-3">
<div class="form-group">
<label>Customer Number</label>
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-hashtag"></i></span>
<input name="CustomerNumber" type="number" class="form-control" onkeydown="return FilterInput(event)" onpaste="handlePaste(event)" required>
</div>
</div>
<!-- /.form-group -->
</div>
<!-- /.col -->
How would I achieve this? I know for
type="text"
it allows limiting spaces by using "maxlength."
One way to do this is to trap the input, check if it passes your validation checks, and if so, proceed, if not, set it to the last known good value, like so:
var oldValue = "";
// listen for "input" event, since that handles all keypresses as well as cut/paste
document.getElementById("myInput").addEventListener('input', function (event) {
var input = event.target;
if (validateInput(input.value)) {
// update old value with new value
oldValue = input.value;
}
else {
// set value to last known valid value
input.value = oldValue;
}
});
function validateInput(str) {
// check length, if is a number, if is whole number, if no periods
return /^[0-9]{0,5}$/.test(str);
}
Test: <input type="text" id="myInput"/><br/>
Try typing/pasting invalid input
all the answers given here previously before mine are all outdated previous
I think solving this question is best answered by
Javascript slice is used to maintain character length
Javascript replace to maintain only numbers are taken
javascript oninput event to prevent the user does not use copy and paste to inject / input invalid character javascript.
<script>
function validate(field) {
let val = field.value;
let data = val.replace(/[^0-9]/g, "");
field.value = data.slice(0,16);
}
</script>
<label for="atmno">Payment card Number</label>
<input name="atmno" type="text" oninput="validate(this)">
I briefly described the answer on an article I wrote here: https://shopinson.com/javascript/javascript-validates-payment-card-number/
Well you could instead of choosing a number type input, use a text type input, where the maxlength attribute works and throw an error with JavaScript if the value is not a number. Like,
if(isNaN(input.value)){ // error code here }
A pure js and dom manipulation solution
Adding an Id attribute for simplicity
<input type="number" id="in" />
We're going to listen for the keypress event and do nothing if the max length is met or a period is entered, i'm using 5 as the max.
let input = document.getElementById('in');
input.addEventListener('keypress',function test(e){
if(input.value.length==5 || e.key=='.')
e.preventDefault();
});
You can run a validation check in your filterInput method.
document.querySelector('.input-group .form-control').addEventListener('keyup', function() {
var keyCode = ('which' in event) ? event.which : event.keyCode;
isNotWanted = (keyCode == 69);
if (this.value.length > this.maxLength) {
this.value = this.value.slice(0, this.maxLength);
}
return !isNotWanted;
});
<div class="col-md-3">
<div class="form-group">
<label>Customer Number</label>
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-hashtag"></i></span>
<input maxlength="5" name="CustomerNumber" type="number" class="form-control" required>
</div>
</div>
<!-- /.form-group -->
</div>
<!-- /.col -->

Validating Contact Number in javascript

I am having a textbox and a div in my form like this :
<input type="text" name="NContact" placeholder="New Contact No." id="txtNewContact"/>
<div id="divCheckContact">
Now on every key press of a key in NContact I need to check if the value entered is a number or not and also it is 10 digit number.And display message in the divison
How to do it Please help.
You can add a pattern and title to do this:
<input type="text" pattern="\d{10}" title="Type 10 digits please" />
The above will check for 10 digit number and if it isn't valid the title will be displayed.
Demo
Note: This is part of html5 spec. Will not work for IE 9 and below.
You can also do it in pure js:
var elem = document.getElementById('txtNewContact');
elem.onkeydown = function(){
if(!/\d{10}/.test(elem.value)){
alert("Type 10 digits please");
}
}
use this
Example
$('#txtNewContact').keyup(function(){
var re = isNaN($(this).val());
if(!re)
{
$('#divCheckContact').html("");
}else
{
$('#divCheckContact').html("please enter only numbers");
$(this).val('');
}
if($(this).val().length>10)
{
$('#divCheckContact').html("please enter only ten 10 digits contact no");
return false;
}
});

Categories

Resources