Javascript Phone Validation - javascript

I want if phone number starts with + it should accept 12 digits if it does not contain + it should accept 10 digit what changes I have to do?
My code is attached below.
function phvalid()
{
var a = document.getElementById('phone').value;
var gb = /^([0|\+[0-9]{1,5})?([7-9][0-9]{9})$/;
if (a=="") {
document.getElementById('ph').innerHTML="Enter Number";
}
if (a.match(gb))
{
document.getElementById("ph").innerHTML="";
// return true;
}
if(a.length!=10)
{
document.getElementById("ph").innerHTML="Enter 10 digits";
return false;
}
if(a.indexOf("+")==0)
{
document.getElementById("ph").innerHTML="Enter 12 digits";
return false;
}
else
{
document.getElementById('ph').innerHTML="";
}
}

Hope this will help you..!! I have used the simple startwith method.
function phoneValidator() {
var number = document.getElementById('phoneNumber').value
if(number.startsWith("+")) {
document.getElementById("phoneNumber").maxLength = 12;
}
else {
document.getElementById("phoneNumber").maxLength = 10;
}
}
<input type="text" name="phoneNumber" id="phoneNumber" onkeyup="phoneValidator()"/>

Firstly, your check for 10 digits overrides your check for 12. What I would do is:
function phvalid()
{
let phone = document.getElementById('phone');
let regex = /^([0|\+[0-9]{1,5})?([7-9][0-9]{9})$/;
if (phone.value=="") {
phone.innerHTML="Enter Number";
}
if (phone.value.match(regex))
{
phone.value.innerHTML="";
// return true;
}
if ( phone.value.charAt(0) != '+' && phone.value.length != 12 ){
if ( phone.value.length != 10 ){
phone.innerHTML = "Please enter a valid phone number, it should be 10 digits unless it is international in which case it should be 12 prefixed by a +";
return;
} else {
// Do whatever you need to do for a 10 digit phone number
}
} else {
// Do whatever you need to do for a 12 digit number
}
}
It is always easier to read your code later if you explain what you are doing, to yourself. The nested if, yes you could do it all on one line or use an iif there but when you come back to read it later, this will probably be easier to understand. I also set the result of the document.getElementById to a variable for both less typing and to make it clear what you are modifying. Your code you are modifying a different element. If that's what you are trying to do, it is still easier than calling getElementById every time you wish to modify it, calling and storing it means you only have to change it in one place if your code changes later instead of having a weird bug because you forgot to change it somewhere.
If I'm reading your regex right, the 10 digit phone number must start with a 0? It might be better to use:
let regex=/(^\+?\d{10,12}$)/;

Related

Find the output using typeof function

I am writing a code. And here I have a problem how can I fix that. I have an input line, it takes a string or a number. So I need to check what is the output and get the answer. I need to give a simple solution. So I can't use functions or something like that.
let input = prompt('Enter your text.');
if (typeof input === "string") {
alert("You have string.");
} else if (typeof input === "number" && input > 30) {
alert("number more than 30");
} else if (typeof input === "number" && input < 30) {
alert("number less then 30");
}
prompt will always return a string.
If you want to check whether the string is composed purely of numerical values, you could use a regular expression:
if (/^[+-]?\d+(?:\.\d+)?$/.test(input)) {
// then it's purely numerical
const num = Number(input.trim());
// perform more operations on the number
} else {
// it's not composed of only numerical characters
}
If you don't want to use a regex, you can use Number alone, but then you'll also include values like Infinity which might not be desirable, and since Number('') gives 0, you'll have to check for that separately:
const num = Number(input);
if (input.trim().length && !Number.isNaN(num)) {
// then it's a number, use num
}
Another approach that I'd recommend is to avoid prompt entirely. Consider using a proper modal instead, such as a form with an input box and a submit button.
In such a case, if you want to require a numeric input, just do:
<input type="number">
I had a similar problem a few weeks ago and this is what I did:
function testNumber(test) {
if (isNaN(test) === false) {
console.log("this is a number");
} else {
console.log("this is not a number");
}
}
testNumber(4); // number
testNumber("4") // number
testNumber("string") // not a number
You can replace "test" for a variable if you don't want to use a function
if (isNaN(myVar) === false) {}
And you may want to add more checks if you want to differentiate between 4 and "4"
You can do
let input = prompt('Enter your text.');
if(isNaN(Number(input))){alert("You have string.")};
if (Number(input) > 30) {
alert("number more than 30");
} else if (Number(input) < 30) {
alert("number less then 30");
}
So it can change all Stringed-numbers to numbers and check if they are number with the isNaN function

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;
}

Javascript Eval() thinks first value is a function

I am writing a function that will evaluate expressions in an input field and return the sum.
Currently is working but I am running into an error that I just cannot figure out. Here is my code in Plunker.
function linkFunction(scope) {
var PO = 10;
scope.value = PO;
scope.result = '';
scope.Evaluate = function (input) {
if (input.match(/[a-zA-Z]/g) != null) { //to check if user has inputted a letter between a-z, case sensitive.
return alert("You must only use numbers, not letters")
} else if (input.match(/[!"^£$&[{}\]?\\##~<>_'|`¬:;,=]/g) != null) { //to check if user has inputted a special symbol
return alert("You must only use the symbols specified")
} else if (input.match(/\.\d*\.+/g) != null) { //to check if user has inputted a doubled decimal eg 10.2.2
return alert("You can only use 1 decimal point")
} else if (input.match(/\.{2,}/g) != null) {//to check if user has inputted a two decimals eg 10..1
return alert("You cannot put two decimals one after another")
}
// if (input.match(/\d*\(\d\W\d\)/g) != null){
// }
var percentPattern = /[0-9]*\.?[0-9]+%/g;
var expressionResults = input.match(percentPattern);
if (scope.enablePercentage) { //if parameter = 1, then do this code.
if (expressionResults != null) { //if user has entered into the input field
if (expressionResults.length > 1) { //if you user has finished the RegEx (%, is the end of the RegEx, so code will think its the end of the array, therefore you cannot add another %)
return alert("Too many % values");
} else {// user has met all requirements
var percentageValue = parseFloat(expressionResults) * PO / 100;
input = input.replace(expressionResults, percentageValue);
}
}
} else if (expressionResults != null) { //if parameter = 0, then do this code. Parameter is off, but user has entered percentage
return alert("You cannot use %");
}
scope.result = eval(input);
}
}});
If you write 10(5+3) it gives you an error
TypeError: 10 is not a function
Obviously if a user ran this code they would expect to see the value 80.
Eval thinks that 10() is a function.
Does anyone know how to fix this problem. Thanks
eval expects you to pass it JavaScript, not algebra.
If you want to multiply two values together then you must use a Multiplicative Operator.
10 * (5+3)

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() );

Max and Min for an Input

For this particular existing form there is an input to accept phone numbers. It already validates to only accept numbers and added a max character attribute for 10 characters.
However someone could add 1-9 digits. So I need to add javascript to check to make sure the character count for that field is 10. The input has an ID of phonenumber.
Can someone tell me how to modify the following code to make that work? Note: The "= 10 Characters" is just a placeholder, that part needs to be replaced with real code.
function checkEmail(theForm) {
if (theForm.getElementById("phonenumber").value = 10 Characters )
{
alert('Your phone number is not 10 digits.');
return false;
} else {
return true;
}
}
I think you want .length
if (theForm.getElementById("phonenumber").value.length == 10) {
You may want to be gentle with your users, and allow common conventions in phone numbers,
like spaces or dash-hyphens.
Just check for 10 digits.
When you use the value, remove any non digits.
function checkphone(v){
if(v.match(/\d/g).length==10) return true;
throw 'Phone number must have 10 digits';
}
checkphone('207 555-5555');
if (theForm.getElementById("phonenumber").value.length != 10)
...since you want something to happen if the length is not 10.
Verify min and max length of phone number field using Javascript Validation
function checkLimit() {
var x, text;
// Get the value of the input field with id="Phone"
phone = document.getElementById("Phone").value;
// If phone is Not a Number or less than 10 or greater than 10
if (isNaN(phone) || phone.length < 10 || phone.length > 10) {
text = "Input not valid";
} else {
text = "Input OK";
}
document.getElementById("resp").innerHTML = text;
}
<input onkeypress="checkLimit()" id="Phone" name="Phone" type="number" class="form-control" placeholder="Phone Number" required="required"/>
<p id="resp"></p>
try this:
function checkEmail(theForm) {
if (theForm.getElementById("phonenumber").value.length != 10 )
{
alert('Your phone number is not 10 digits.');
return false;
} else {
return true;
}
}

Categories

Resources