textbox one with number only and another with comma in jquery - javascript

I have two text box in a form. One verifies for number only and another one for number and comma.
1st case number only.
function(textBoxObject) {
var that = $(this),
val = that.val();
if (val === "" || isNaN(val)) {
that.addClass("error");
} else {
that.removeClass("error");
}
}
2nd case number and comma.
How do I handle another textbox which takes numbers and commas? And is it possible to add the logic in the first function itself?

I assume you treat 12,34 as illegal and 1,234 as legal. Then here's the demo
function checkNumberWithComma(textBox) {
if ((textBox.value == 0 || textBox.value) && textBox.value.match(/^\d{0,3}(?:,\d{3})*$/)) {
$(textBox).removeClass("error");
}
else {
$(textBox).addClass("error");
}
}
And the regular expression:
^ means start
\d{0,3} means 0-3 digits
(?: means non-capturing group
,
\d{3} means 3 digits
)
* means repeat for 0 or more times
$ means end

You can use .indexOf() method.
something like...
if(val.indexOf(',') === -1) {
...your code here...
}

You could try and use if(val.match(/^(\d,?)*$/g))
It will allow an empty string, numbers and numbers seperated by commas. It does allow commas at the end of the string, though.
So, 1,2,3,4, 1234 and 1234, all pass, but ,12,34 and foo will fail.

Take a look a this codepen, I don't know exactly the behaviour you want but you can try something similar.
JS
$(function(){
function validateInput() {
var that = $(this),
val = that.val();
if (that.attr('data-type') === 'number') {
if (val === '' || isNaN(val)) that.addClass('error');
else that.removeClass('error');
}
else {
if (val.indexOf(',') === -1) that.addClass('error');
else that.removeClass('error');
}
}
$('input').change(validateInput);
});
HTML
<div>
<label> Number
<input type="text" data-type="number"/>
</label>
</div>
<div>
<label> Comma
<input type="text"/>
</label>
</div>

Related

How do I format my input field using replace regex with javascript and jQuery?

I want to format my <input id="phone_number" type="tel" name="phone_number" maxlength="14"> to have a value like this (123) 456-7890
My current jQuery code:
jQuery("#phone_number").on("keypress", function(event) {
var phoneReg = /[0-9]/g;
var phoneKey = String.fromCharCode(event.keyCode);
if(!phoneReg.test(phoneKey)){
// dont display characters
return false;
} else {
// display numbers only
var phoneNumberVal = jQuery("#phone_number").val();
var phoneNumberUsFormat = phoneNumberVal.replace(/(\d{3})(\d{3})(\d{2})/,"($1) $2-$3");
jQuery("#phone_number").val(phoneNumberUsFormat);
}
});
The code above can format a phone number like this: (123) 456-7890 only after typing all the numbers.
What I want to happen is start adding a parentheses and a dash when the user reaches the 3rd and 6th digit
What I currently tried is this:
jQuery("#phone_number").on("keypress", function(event) {
var phoneReg = /[0-9]/g;
var phoneKey = String.fromCharCode(event.keyCode);
if(!phoneReg.test(phoneKey)){
// dont display characters
return false;
} else {
// display numbers only
if(phoneNumberVal.length < 4) {
newNumber = phoneNumberVal.replace(/(\d{3})/,"($1) ");
jQuery("#phone_number").val(newNumber);
}
}
});
The problem with the updated code above is not being able to detect the 6th digit then automatically add a -
Any help is greatly appreciated. Thanks
I suggest you to follow that process:
If the current input's value is not corresponding to the (XXX) XXX-XXXX format, checks the number of digits only.
If more or exactly 6 (= XXXXXX...), converts to (XXX) XXX- plus the rest if present.
Else if bewteen 3 and 6 (= XXX...), converts to (XXX) plus the rest if present (note the last space in the format I wrote).
Then updates the input's value.
Else if the displayed format is right, just avoid the possibility to type more characters.
The code snippet below (with some bonuses):
$('#telephone').on('keyup', function(e) {
// If not removing a character...
// (Without that check, you'll not be able to remove characters correctly.)
if (e.key !== 'Backspace') {
let value = $(this).val();
// If the value is not corresponding to wanted format...
if (!/\(\d{3}\) \d{3}-\d{4}/.test(value)) {
// Only keeps digits.
value = value.replace(/[^\d]/g, '');
// If we have at least 6 digits, converts the value to "(XXX) XXX-...".
if (value.length >= 6) {
value = `(${value.substring(0, 3)}) ${value.substring(3, 6)}-${value.substring(6)}`;
}
// If we have at least 3 digits (but less than 6), converts the value to "(XXX) ...".
else if (value.length >= 3) {
value = `(${value.substring(0, 3)}) ${value.substring(3)}`;
}
// Updates the input's value.
$(this).val(value);
}
// If the format is correct, just avoid to have too much characters.
else {
$(this).val(value.substring(0, 14));
}
}
});
// Doesn't display unwanted characters.
// (Did this on a different event. Try replacing "input" by "keyup" to see why.)
$('#telephone').on('input', function() {$(this).val($(this).val().replace(/[^\d() -]/g, ''));});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="telephone">
Try something like this after the 6th character?
$("input[name='phone']").keyup(function() {
$(this).val($(this).val().replace(/^(\d{3})(\d{3})(\d)+$/, "($1)$2-$3"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input name="phone" maxlength="14" />

Validate number formats in a contact form (javascript)

I have a function to validate phone number in a contact form, but i need to be able to put in "xxx xxx xxxx" for example, and not just "xxxxxxxx"
The number format should be:
xxx xxx xxxx
xxx-xxx-xxxx
xxx.xxx.xxxx
function validatePhone() {
var phone = document.getElementById("phone").value;
if (phone.length == 0) {
var w = document.getElementById("phoneError").textContent;
alert(w);
return false;
}
if (phone.length != 10) {
var r = document.getElementById("phoneError").textContent;
alert(r);
return false;
}
// THIS IS NOT WORKING
if (
!phone.match(/^[0-9]{10}$/) ||
!phone.match(/^\d{3}-\d{3}-\d{4}$/) ||
!phone.match(/^\d{3}.\d{3}.\d{4}$/)
) {
var t = document.getElementById("phoneError").textContent;
alert(t);
return false;
}
}
Two things: First, you are mixing up AND and OR:
if (
!phone.match(/^[0-9]{10}$/) ||
!phone.match(/^\d{3}-\d{3}-\d{4}$/) ||
!phone.match(/^\d{3}.\d{3}.\d{4}$/)
) {
As soon as one of the conditions fails, it will return false (which is basically always). You want this if to apply, when none of the expressions matches, e.g. when all of them are false. Therefor, you have to use && instead of ||. Not a AND not b AND not c.
Second: your 3rd regex is a bit off: . means "any character", so this regex would also match "123x123y1234". You need to escape the dot with a backslash: /^\d{3}\.\d{3}\.\d{4}$/
Also, you can improve this code significantly. You have 5 conditions, which could all be handled in one (if you want to allow the input of "123.123 234", otherwise you will have to do it using 3 regex). And for just checking if a regex matches a string, you maybe should use test(), because it is just slightly faster (it won't matter in your case, but just out of principle).
You can reduce your code to:
if (/^\d{3}[\s-.]\d{3}[\s-.]\d{4}$/.test(document.getElementById("phone").value) === false) {
alert (document.getElementById("phoneError").textContent);
return false;
}

Validating phone number with different formats WITHOUT regex

In JavaScript, I need validate phone numbers without using regular expressions (must be with string manipulation). The phone numbers have to be in one of the following formats:
123-456-7890
1234567890
(123)4567890
(123)456-7890
Then I must also provide an alert if the phone number isn't in one of the formats listed above.
I have only been able to manage to get #2 working, which looks something like this:
function len(gth)
{
if (gth.value.length != 10)
{
alert("Telephone numbers MUST be 10 digits!");
}
}
which down in the HTML it would call up to the function:
<p>Phone: <input id = "phone" onblur="len(this)" name = "Phone" size = "20" type = "text" maxlength = "10"> </p>
Since you need a solution without regex, I believe this should work.
const phones = [
'123-456-7890',
'1234567890',
'(123)4567890',
'(123)456-7890',
'+61(123) 456-7890',
'12345',
'))))01/34$89.77(99'
]
function len(gth) {
if (gth.substring(3, 4) == '-' && gth.substring(7, 8) == '-') // 123-456-7890
gth = gth.replace('-', '').replace('-', '');
else if (gth.substring(0, 1) == '(' && gth.substring(4, 5) == ')' && gth.substring(8, 9) == '-') // (123)456-7890
gth = gth.replace('(', '').replace(')', '').replace('-', '');
else if (gth.substring(0, 1) == '(' && gth.substring(4, 5) == ')') // (123)4567890
gth = gth.replace('(', '').replace(')', '');
if (!isNaN(gth) && gth.length == 10) {
return true;
}
alert("Telephone numbers:" + gth + " MUST be 10 digits!");
}
phones.forEach(len)
I would replace the numbers with something like x, then check against predefined patterns:
function check(num) {
let pattern = '';
for (let i = 0; i < num.length; i++) {
pattern += num[i] >= '0' && num[i] <= '9' ? 'x' : num[i];
}
return ['xxx-xxx-xxxx', 'xxxxxxxxxx', '(xxx)xxxxxxx', '(xxx)xxx-xxxx']
.indexOf(pattern) >= 0;
}
For extra credit, find the bug in the above program.
However, you don't really need to do any of this. You should be able to use the pattern attribute on the input element. That will also provide a better user experience. For instance, you can style the input element using the :invalid pseudo-class, by putting a red border around it for example, to give the user real-time feedback that their input is not valid. Yes, that takes a regular expression--what was your reason for not wanting to use a regular expression again?
You can make it manually be:
Checking string size if it is the expected or not
split the string to char array then parse them as integers inside a try block if numberFormatException is thrown it should be a bracket ( ) or -
Basic example of extracting the input data to Array
function test() {
var phnTest = document.getElementById('phone').value;
var strArray = [];
strArray = phnTest.split('');
document.getElementById('p').innerHTML = strArray;
}
<form action="demo_form.asp">
Phone <input id="phone" type="text" name="phone"><br>
<input type="button" value='Submit' onclick="test()">
</form>
<p id='p'></p>
This is dependent on how the data is structured, if you need to search a body of text and so on, but basics would be...
If it's a simple pull from an <input>, grab the data...
Take the input data, and generate an array with each character. You could then test, say strArray[3], for a dash or a dot. If not present, it can continue along to check for seven numbers in a row and so on.
This is going to be extremely consuming and require a number of conditionals to be checked. I assume the "without RegEx" is a requirement for a project or such, if not, recommend learning and using RegEx.
Hope this gets you going.
This is my attempt. The key is creating an array from the string then filtering out any non numerical characters. It would be easier to use regular expression though. just
number.replace(/(\D+)/g, '')
const numbers = [
'123-456-7890',
'1234567890',
'(123)4567890',
'(123)456-7890',
'+61(123) 456-7890',
'12345',
'))))01/34$89.77(99'
]
// validate a phone number
function validate(number) {
const digits = clean(number)
console.log({
number,
digits,
length: digits.length,
pass: digits.length === 10
})
}
// remove any non digits from the number
function clean(number) {
return Array.from(number).filter(char => {
return !isNaN(char) && char !== ' '
}).join('')
}
numbers.forEach(validate)

Restrict text input to number groups separate by a non-consecutive character

I've been doing a lot of searching, chopping and changing, but I'm...slightly lost, especially with regards to many of the regex examples I've been seeing.
This is what I want to do:
I have a text input field, size 32.
I want users to enter their telephone numbers in it, but I want them to enter a minimum of 10 numbers, separated by a single comma. Example:
E.g. 1
0123456789,0123456789 = right (first group is >=10 numbers, second group = >=10 numbers & groups are separated by a single comma, no spaces or other symbols)
E.g. 2
0123456789,,0123456789 = wrong (because there are 2 commas)
E.g. 3
0123456789,0123456789,0123456789 = right (same concept as E.g. 1, but with 3 groups)
I've got the following, but it does not limit the comma to 1 per 10 numbers, and it does not impose a minimum character count on the number group.
$(document).ready(function(){
$("#lastname").keypress(function (e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && String.fromCharCode(e.which) != ','
&& (e.which < 48 || e.which > 57)) {
//display error message
$("#errmsg").html("Digits Only").show().fadeOut("slow");
return false;
}
});
});
Preferably, I'd like to warn the user of where they are going wrong as well. For example, if they try to enter two commas, I'd like to specifically point that out in the error, or if they havent inserted enough numbers, i'd like to specifically point that out in the error. I'd also like to point out in the error when neither a number or a comma is inserted. I'd like to ensure that the tab, and F5 keys are not disabled on the keyboard as well. And very importantly, I'd like to specifically detect when the plus or addition key is used, and give a different error there. I think I'm asking for something a little complex and uninviting so sorry :/
The example code I provided above works pretty well across all browsers, but it doesn't have any of the minimum or maximum limits on anything I've alluded to above.
Any help would be appreciated.
As far as a regex that will check that the input is valid (1-3 phone numbers of exactly 10 digits, separated by single commas), you can do this:
^\d{10}(,\d{10}){0,2}$
Try like the below snippet without Regex
var errrorMessage = '';
function validateLength (no) {
if(!no.length == 10) {
return false;
}
return true;
}
function validatePhoneNumbers (currentString, splitBy) {
if(currentString) {
var isValid = true,
currentList = currentString.split(splitBy);
// If there is only one email / some other separated strings, Trim and Return.
if(currentList.length == 1) {
errrorMessage = 'Invalid Length in Item: 1';
if(validateLength( currentString.trim() )) isValid = false;
}
else if(currentList.length > 1) {
// Iterating mainly to trim and validate.
for (var i = 0; i < currentList.length; i++) {
var listItem = currentList[i].trim();
if( validateLength(listItem ) ) {
isValid = false;
errrorMessage = 'Invalid Length in Item:' + i
break;
}
// else if for some other validation.
}
}
}
return isValid;
}
validatePhoneNumbers( $("#lastname").val() );

Javascript check for spaces

I have this function but I want to check for spaces only in the front and back, not in the middle before i sent back what can i do with it...
function validateNumeric() {
var val = document.getElementById("tbNumber").value;
var validChars = '0123456789.';
for(var i = 0; i < val.length; i++){
if(validChars.indexOf(val.charAt(i)) == -1){
alert('Please enter valid number');
return false;
}
}
return true;
}
Time for regular expressions.
function startsOrEndsWithWhitespace(str)
{
return /^\s|\s$/.test(str);
}
Tests:
> /^\s|\s$/.test('123454')
false
> /^\s|\s$/.test('123 454')
false
> /^\s|\s$/.test(' 123454')
true
> /^\s|\s$/.test(' 123454 ')
true
> /^\s|\s$/.test('123454 ')
true
if i dont wanna accept 1 1 what do i have to change
function containsWhitespace(str)
{
return /\s/.test(str);
}
Tests:
> /\s/.test('123454')
false
> /\s/.test('123 454')
true
> /\s/.test(' 123454')
true
> /\s/.test('123454 ')
true
> /\s/.test(' 123454 ')
true
> /\s/.test(' 123 454 ')
true
For a really simple solution, if you can use jQuery, use jQuery.trim() and compare the trimmed string with the original. If not equal, then there were spaces so the number is invalid.
function trim (myString)
{
return myString.replace(/^\s+/g,'').replace(/\s+$/g,'')
}
source
To trim your string you can write something like this, as it's been said before:
function trim(str){
return str.replace(/^\s+|\s+$/g), '');
}
But why bother?
Want you really want is:
function validateNumeric(str) {
return !isNaN(parseFloat(str));
}
Note your original code accepts something like "..." or "7.8..9" as being numeric, which is wrong.
Update: kennebec has called my attention to the fact that parseFloat() will ignore trailing garbage at the end of string. So I call your attention to this alternative given in an answer to question "Validate numbers in JavaScript - IsNumeric()":
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
(Original credit goes to CMS).
function validateNumeric() {
var val = document.getElementById("tbNumber").value;
if (!/^\s*(?:\d+(?:\.\d*)?|\.\d+)\s*$/.test(val)) {
alert('Please enter a valid number');
return false;
}
return true;
}
(?:\d+(?:\.\d*)|\.\d+) breaks down as follows:
\d+ is any number of digits, e.g. 123
(\.\d*)? optionally matches a fraction, e.g. .25 and . or blank but not .1.2
\.\d+ matches a fraction without an integer part as in .5 but not 1.5.
(?:abc|def) groups things together and matches either abc or def
/^\s*(?:\d+(?:\.\d*)|\.\d+)\s*$/ means any number of spaces followed by one or more decimal digits followed by any number of spaces. So it does what your validChars loop did plus allows spaces at the start and end.

Categories

Resources