Extract substring out of a user input phone number using Javascript - javascript

I am getting phone number input from user as +XXX-X-XXX-XXXX that (+XXX as country code), (X as city Code), (XXX as 1st 3 digits) and , (XXX as 2nd 4 digits). I used regular expression to confirm the entry as in following code;
function validate(form) {
var phone = form.phone.value;
var phoneRegex = /^(\+|00)\d{2,3}-\d{1,2}-\d{3}-\d{4}$/g;
//Checking 'phone' and its regular expressions
if(phone == "") {
inlineMsg('phone','<strong>Error</strong><br />You must enter phone number.',2);
return false;
}
if(!phone.match(phoneRegex)) {
inlineMsg('phone','<strong>Error</strong><br />Enter valid phone <br />+xxx-x-xxx-xxxx (or) <br />00xxx-x-xxx-xxxx.',2);
return false;
}
return true;
}
Its working very fine but the problem is that
EDIT : If the user inputs as +XXXXXXXXXXX (all together) and hit enter or go to another field, the input it self set according to the Regex that is +XXX-X-XXX-XXXX.
Can some one guide me with some example how to do this task.
Thank you

Set the element's onblur method a callback as follows:
var isValidPhoneNumber = function(string) {
...
}
var reformat = function(string) {
/*
* > reformat('example 123 1 1 2 3 123-45')
* "+123-1-123-1234"
*/
var numbers = string.match(/\d/g);
return '+' + [
numbers.slice(0,3).join(''),
numbers.slice(3,4).join(''),
numbers.slice(4,7).join(''),
numbers.slice(7,11).join('')
].join('-');
}
var reformatPhoneNumber = function() {
var inputElement = this;
var value = inputElement.value;
if (isValidPhoneNumber(value))
inputElement.value = reformat(inputElement.value);
else
// complain to user
}
Here are two example ways you could set the onblur callback handler:
document.getElementById('yourinputelement').onblur = reformatPhoneNumber;
<input ... onblur="reformatPhoneNumber"/>
You can augment reformatPhoneNumber with more validation code if you'd like, or just constantly validate the number as the user is typing it.
To only do this if your phone number is of the form +ABCDEFGHIJK, then add an string.match(/^\+\d{11}$/)!==null to your if statement. (^,$ mean the start and end of the string, \+ means a plus sign, and \d means a digit 0-9, repeated exactly {11} times). Specifically:
function isPlusAndEleventDigits(string) {
/*
* Returns whether string is exactly of the form '+00000000000'
* where 0 means any digit 0-9
*/
return string.match(/^\+\d{11}$/)!==null
}

Try shaping the input:
result = subject.replace(/^((\+|00)\d{2,3})-?(\d{1,2})-?(\d{3})-?(\d{4})$/mg, "$1-$3-$4-$5");
Then do next procedure.

Related

How to validate single lines in Html TextAreaFor against regular expression(s)

I am stuck with the following problem. On a web page in my current C# / MVC project, I added some control elements to fill a model. Among these control elements is a text area, designed using #Html.TextAreaFor:
<div class="smt-textarea ">
#Html.LabelFor(m => m.Numbers):
#Html.TextAreaFor(m => m. Numbers, new
{
#class = "form-control",
id = "smt-textarea",
rows = 25,
})
</div>
Users should enter a sequence of numbers into that text area. The number sequence follows a specific pattern. The pattern is later evaluated in code-behind methods, which are working well, and which are not part of my question here.
As a new feature, the numbers entered in the text area should now be validated regarding the amount of numbers in the actual sequence. The rule states that only digits from 0-9 can be entered in the text area. A number sequence should consist of exactly 19 digits.
Since I need to directly access the text area, I figured it might be a good idea to opt for Javascript in this particular case. I should note that I am quite new to JS and this might be one part of the problem. Be that as it may, based on some posts here on SO, I came up with the following preliminary solution.
console.log(textArea.value);
var reg = /\d{19,19}/;
let regex = new RegExp(reg);
if (regex.test(textArea.value)) {
console.log(regex.test(textArea.value));
alert("IT'S A MATCH !!!");
} else {
alert("SORRY, NO MATCH.");
}
}
window.onload = function () {
var textArea = document.getElementById("smt-textarea");
textArea.onkeyup = function (evt) {
evt = evt || window.event;
if (evt.keyCode === 13) {
validateTextArea(this);
}
};
};
Unfortunately, the code seems to validate the entire text area, meaning I do get a match whenever there are one more digit sequences matching the pattern, e.g. when entering the following
12345
0276114931111401167
skjfsjgrs
ksgfskgjsgjsrgs
skjfsjgrs and ksgfskgjsgjsrgs are valid because they are preceded by a "valid" number sequence.
What I would like to accomplish is that upon pressing the <ENTER> key, only the current line of the text area should be validated against the regular expression outlined in the sample. If the current line does not match, a warning message should be displayed. Once the user corrected his/her digit sequence, validation should continue moving to the next line until the next error pops up.
At the moment your validation will be passed if your string from text area contains a sequence from 19 numbers. In order to make sure each line is valid you'd better use ^ and $ anchors to match the whole string from start to end. Something like this:
/^(\d{3}\n?)*$/
var textArea = document.getElementById("smt-textarea");
textArea.onkeyup = function(evt) {
evt = evt || window.event;
if (evt.keyCode === 13) {
validateTextArea(this);
}
};
function validateTextArea(textArea) {
let regex = new RegExp(/^(\d{19}\n?)*$/);
if (regex.test(textArea.value)) {
alert("IT'S A MATCH !!!");
} else {
alert("SORRY, NO MATCH.");
}
}
<textarea name="" id="smt-textarea" rows="25"></textarea>
Also it might be a good idea to trim your string value in order to avoid problems with white-space characters in the end.
Update
Here is another version which validate line by line:
var textArea = document.getElementById("smt-textarea");
textArea.onkeyup = function(evt) {
evt = evt || window.event;
if (evt.keyCode === 13) {
validateTextArea(this);
}
};
function validateTextArea(textArea) {
let lines = textArea.value.trim().split('\n');
let regex = new RegExp(/^\d{19}$/);
let invalid = lines.some(function(line, index) {
let lineInvalid = !regex.test(line);
if (lineInvalid) {
alert(`Line ${index+1} is invalid`);
}
return lineInvalid;
});
console.log(`Text area is ${(invalid ? 'invalid' : 'valid')}`);
}
<textarea name="" id="smt-textarea" rows="25"></textarea>

How do I format input phone number without plugin in jQuery?

I want to format my <input id="phone_number" type="tel"> on keypress
The requirements of my input field are:
numbers only and no letters and other special characters
format the input field with a US number like (123) 457-7890
This is my current code:
jQuery("#phone_number").on("keypress", function(event) {
var reg = /[0-9]/g;
var key = String.fromCharCode(event.keyCode);
if(!reg.test(key)){
// return false if NOT number
return false;
} else {
// numbers only
var phone_value = jQuery("#phone_number").val();
var number = phone_value.replace(/(\d{3})(\d{3})(\d{2})/,"$1-$2-$3");
jQuery("#phone_number").val(number);
}
});
Problem: The problem with my code is that it is not able to limit length of my input
Final Output should look like (123) 457-7890 first 3 digits enclosed in a parentheses
Any help is greatly appreciated. Thanks
I guess this should give you what is needed. You were very close to the answer.
I have limited the length of <input> using the maxlength attribute and added parenthesis in your phone_value.replace() function surrounding $1.
jQuery("#phone_number").on("keypress", function(event) {
var reg = /[0-9]/g;
var key = String.fromCharCode(event.keyCode);
if(!reg.test(key)){
// return false if NOT number
return false;
} else {
// numbers only
var phone_value = jQuery("#phone_number").val();
var number = phone_value.replace(/(\d{3})(\d{3})(\d{2})/,"($1) $2-$3");
jQuery("#phone_number").val(number);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="phone_number" type="tel" maxlength="14">

What regex should i use to validate a number pattern?

For this first validate I try to validate an input of 4 digits, however when i try to run it and enter 4 digits the error still shows up:
function pCodeValidate() {
var pCode = document.getElementById("postcode");
var pCodePattern = /^\d{4}$/;
if (!(pCodePattern.test(pCode))){
errorList("post code must be 4 digits")
}
//return
}
The second one validates a mobile number with the pattern "04dddddddd, where d is a digit". this is my code:
function mNumberValidate() {
var mNumber = document.getElementById("mobilenumber");
var mNumberPattern = /^\d{10}$/;
if (!(mNumberPattern.test(mNumber))){
errorList("invalid mobile number");
}
//return
}
For this second part what regex should I use to enforce "04" being the first value in the input?
The problem with your first function is that you are not using the regex to test the value of the input, you are trying to test a reference to the input itself. Change the following line:
var pCode = document.getElementById("postcode");
to get the value:
var pCode = document.getElementById("postcode").value;
In your second function you have the same problem, which you'd fix the same way:
var mNumber = document.getElementById("mobilenumber").value;
// --------------------------------- add this part >-^^^^^^
Then the regex you need for a phone number starting with 04 is as follows:
/^04\d{8}$/
That is:
^ - beginning of string
04 - the literal characters "04"
\d{8} - any 8 digits
$ - end of string
(Dodgy demo: https://jsfiddle.net/xah6qstz/)

ServiceNow Script onSubmit not working properly

I am using ServiceNow platform. I am writing a Catalog Client Script to validate form fields on a Catalog Item record producer.
I am stopping the submission of the form by using return false if validation does not pass inspection.
I have tested this by entering invalid data (group name with special characters or a group name that exists already) and it catches the issue and shows the error message. I can enter invalid data and submit multiple times and it works.
However, the issue:
The script seems to "stop" running after I first enter invalid data and submit, and then I correct the data press the submit button again. It just sits there and does nothing. I have to reload the form again which is not desirable.
What is going on with the control flow? How can I cleanly stop the form if the data is invalid, but then allow the user to correct the mistake and press the submit button again to proceed?
I can tell that the script doesn't run again because I have an alert box popping up that says "script run" every time the script runs. It just stops running at some point after submitting invalid data first and then entering some valid data and pressing submit.
function onSubmit() {
g_form.hideAllFieldMsgs('error');
alert("script run");
//Group Name contain letters numbers and dashes only
var group_name = g_form.getValue('u_group_name');
// Group name regular expression
var regGrpName = /^([A-Za-z0-9\-]+)$/;
// Check name against regular expression
if (regGrpName.test(group_name) == false) {
g_form.showFieldMsg('u_group_name', "Group Name must contain only letters, numbers or dashes. ", 'error');
//Do not submit
//g_form.submitted = false;
return false;
}
//Check if google group already exists
var rec = new GlideRecord('u_google_user_accounts');
rec.addQuery('u_account_email', new_group_email);
rec.query();
while (rec.next()) {
g_form.showFieldMsg('u_group_name',rec.u_account_email + " already exists as an account.",'error');
return false;
}
//Group Members Email List separated by commas
// Hide error message
//g_form.hideErrorBox('u_group_members');
var group_members = g_form.getValue('u_group_members');
// Comma separate list
var member_split = group_members.split(',');
// Loop over list of email addresses
for (var n = 0; n < member_split.length; n++) {
// Trim whitespace
var member_info = trim ? member_split[n].trim() : member_split[n];
// Email validation regular expression
var regEmail = /^\w+((-\w+)|(\.\w+))*\#[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
// Check each item against regular expression
if (member_info.search(regEmail) == false) {
g_form.showFieldMsg('u_group_members', "Group Members contains an invalid email address. " + member_info, 'error');
//Do not submit
//g_form.submitted = false;
return false;
} else if (member_info.search(validRegExp) == true) {
g_form.setValue('u_group_members', group_members);
}
}
return true;
}
I'm glad you found a solution above, but I wanted to leave a comment as well, to ask if you've tried a try{} catch{} block to handle invalid data?
I think I have solved the issue. I made a completely separate function that checks the validation. The onSubmit calls the validation function and checks the return value. If the return value is false then it stops the form. Otherwise it is submitted even after multiple attempts with invalid data. I think this will do the trick. Let me know if anyone can see any issues. Thanks for the help.
function onSubmit() {
var isValid = checkGoogleGroup();
if (isValid == false) {
g_form.submitted = false;
return false;
}
}
function checkGoogleGroup() {
g_form.hideAllFieldMsgs('error');
//Group Name contain letters numbers and dashes only
var group_name = g_form.getValue('u_group_name');
// Group name regular expression
var regGrpName = /^([A-Za-z0-9\-]+)$/;
// Check name against regular expression
validGroupName = regGrpName.test(group_name);
if (validGroupName == false) {
g_form.showFieldMsg('u_group_name', "Group Name must contain only letters, numbers or dashes. ", 'error');
//Do not submit
return false;
}
//Check if google group already exists
var rec = new GlideRecord('u_broad_user_accounts');
rec.addQuery('u_account_email', new_group_email);
rec.query();
while (rec.next()) {
g_form.showFieldMsg('u_group_name',rec.u_account_email + " already exists as an account.",'error');
return false;
}
//Group Members Email List separated by commas
var group_members = g_form.getValue('u_group_members');
// comma separate list
var member_split = group_members.split(',');
// loop over list of email addresses
for (var n = 0; n < member_split.length; n++) {
// trim whitespace
var member_info = trim ? member_split[n].trim() : member_split[n];
// validation regular expression
var validRegExp = /^\w+((-\w+)|(\.\w+))*\#[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
// check each item against regular expression
if (member_info.search(validRegExp) == -1) {
g_form.showFieldMsg('u_group_members', "Group Members contains an invalid email address. " + member_info, 'error');
return false;
}
}
}

Javascript/Jquery validating decimal input on keyup

I'm trying to find a way to validate a text input on key press, I want to allow numbers only inside my text input including decimals.
I was taking the approach of using jQuery.keydown, and checking what the key was and using.
input numbers max length 999.999
-
my result after . (point) 3 number it is goog. but 99999.999
I need 999.999,222.222,22.01 ->
max length +++.+++
this my code
<input type="text" id="spinEdit2" class="aSpinEdit" />
<script type="text/javascript">
var txt = document.getElementById('spinEdit2');
txt.addEventListener('keyup', myFunc);
function myFunc(e) {
var val = this.value;
var re1 = /^([0-9]+[\.]?[0-9]?[0-9]?[0-9]?|[0-9])/g;
val = re1.exec(val);
//console.log(val);
if (val) {
this.value = val[0];
} else {
this.value = "";
}
}
</script>
Thanks
How about
/^([0-9]{1,3}(?:\.[0-9]{0,3})?)/g
In case you want the details: the {1,3} means the preceding thing can happen from 1 to 3 times. The (?:) is a non-captured group -- it's a grouping of the following symbols, but it doesn't capture to any variables like $1.

Categories

Resources