ServiceNow Script onSubmit not working properly - javascript

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

Related

How can I get my span id’s to display the appropriate messages when user doesn’t follow rules?

I am currently having problems with displaying different span error messages for some of the same input texboxes based on if the user doesn't follow my validation rules. I really could use some suggestions of how I can make some of my if statements better to enforce my rules that I have setup. I am okay with how my if statement is validating the username and how if statement is validating the password, but I have been struggling to try to figure what is the best method for validating my repeatemail textbox and emailaddress textbox. Can someone help me? Thanks in advance! Here is my HTML, CSS, and JavaScript/JQuery code
$('#button2').on('click', function () {
var NewUsernameError = document.getElementById("New_Username_error");
var NewPasswordError = document.getElementById("New_Password_error");
var NewEmailAddressError = document.getElementById("New_Email_error");
// var NewRepeatEmailAddressError=document.getElementById("NewReenter_Email_error");
// How can I get my span id's to display one of two different error //messages based on my rules below? Right now it will only display first error //messages. Do I need to create two different span ids (except for the password // texbox) for each input textbox or is one span id fine how I currently have //it? Shouldn't I be able to display either message just using one span id?
if($(".newUsername").val().length < 6)
{
NewUsernameError.innerHTML= "The username must be at least 6 characters";
// NewUsernameError.innerHTML= "There is an already existing account with username";
}else
{
NewUsernameError2.innerHTML = '';
}
if($(".newPassword").val().length < 6) {
{
NewPasswordError.innerHTML= "The password must be at least 6 characters";
}else{
NewPasswordError.innerHTML = '';
}
if($(".newEmail")== "" && $(".newEmail") != /^[a-zA-Z0-9]#[a-zA-Z])+.[a-z])
{
NewEmailAddressError.innerHTML= "The email must not be left empty.";
NewEmailAddressError.innerHTML= "The email must contain # symbol in it.";
}else{
NewEmailAddressError.innerHTML= '';
}
if($(".repeatEmail").value != $(".newEmail").value && $(".repeatEmail") == ""){
NewRepeatEmailAddressError.innerHTML= "This repeat email doesn't equal to the first one entered.";
NewRepeatEmailAddressError.innerHTML= "This repeat email must not be blank.";
}else{
NewRepeatEmailAddressError.innerHTML= '';
}
.
Lots of problems here.
if($(".newEmail")== "" && $(".newEmail") != /^[a-zA-Z0-9]#[a-zA-Z])+.[a-z])
That tries to compare the <input> element instead of its contents.
if($(".repeatEmail").value != $(".newEmail").value && $(".repeatEmail") == ""){
That tries to compare undefined instead of the form element's contents. (jQuery doesn't use .value.)
Instead, you want .val():
if($(".newEmail").val() == "" && $(".newEmail").val() != /^[a-zA-Z0-9]#[a-zA-Z])+.[a-z])
...
if($(".repeatEmail").val() != $(".newEmail").val() && $(".repeatEmail").val() == ""){
A secondary problem is where you try to assign two error messages simultaneously:
NewRepeatEmailAddressError.innerHTML= "This repeat email doesn't equal to the first one entered.";
NewRepeatEmailAddressError.innerHTML= "This repeat email must not be blank.";
In these cases the second .innerHTML is going to immediately overwrite the first one, so the first error message will never be seen. Each of those errors needs to be in its own, separate if {} condition.
Third, this isn't how to do regex comparisons, that regex contains several syntax errors (no trailing slash, mismatched parens), and even if it worked it would disallow many valid email addresses:
$(".newEmail") != /^[a-zA-Z0-9]#[a-zA-Z])+.[a-z])
Better email address validation regexes can be found in e.g. this question, but even those can disallow some valid addresses. Keep things simple and test only for what the error message claims you're testing for, the presence of an # symbol:
/#/.test($('.newEmail').val())
Putting it all together
Cleaning your original function, converting all the vanilla js into jQuery (there's no real drawback to mixing them other than that it makes the code harder to read, but I figure if you've already got jQuery may as well use it), and rearranging some logic to simplify the code results in this:
var validate=function() {
// clear out the error display ahead of time:
var newUsernameError = $("#New_Username_error").html('');
var newPasswordError = $("#New_Password_error").html('');
var newEmailAddressError = $("#New_Email_error").html('');
var newRepeatEmailAddressError = $("#Repeat_Email_error").html('');
// just to make the later conditions easier to read, let's grab all the values into vars:
var newUsername = $('.newUsername').val();
var newPassword = $('.newPassword').val();
var newEmail = $('.newEmail').val();
var repeatEmail = $('.repeatEmail').val();
// presumably you'll want to prevent form submit if there are errors, so let's track that:
var errorsFound = false;
if (newUsername === "") {
errorsFound = true;
newUsernameError.html("The username must not be empty.");
} else if (newUsername.length < 6) {
errorsFound = true;
newUsernameError.html("The username must be at least 6 characters.");
}
if (newPassword.length < 6) {
errorsFound = true;
newPasswordError.html("The password must be at least 6 characters.");
}
if (newEmail === "") {
errorsFound = true;
newEmailAddressError.html("The email must not be left empty.");
} else if (!/#/.test(newEmail)) {
errorsFound = true;
newEmailAddressError.html("The email must contain an # symbol.");
}
if (repeatEmail !== newEmail) {
errorsFound = true;
newRepeatEmailAddressError.html("This repeat email doesn't equal to the first one entered.");
}
// No need to test for repeatEmail being empty, since that's already covered by the newEmail case above.
// OK, all conditions checked, now:
if (errorsFound) {
// prevent form submit. (If this is called in an onsubmit handler, just return false.)
} else {
// allow form submit.
}
console.log("Errors found: ", errorsFound);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
Username: <input class="newUsername">
<div id="New_Username_error"></div>
Password: <input class="newPassword">
<div id="New_Password_error"></div>
newEmail: <input class="newEmail">
<div id="New_Email_error"></div>
repeatEmail: <input class="repeatEmail">
<div id="Repeat_Email_error"></div>
</form>
<button onclick="validate()">Validate</button>
Keep one container for the errors you might expect to get on the input. I would do something like this to avoid all the else and else if's
$('#button2').on('click', function () {
// VALIDATE USERNAME
var newUserErrStr = '';
var newUsernameVal = $(".newUsername").val();
if(newUsernameVal.length < 6) newUserErrStr += "The username must be at least 6 characters";
document.getElementById("New_Username_error").innerHTML = newUserErrStr;
// VALIDATE PASSWORD
var newPasswordErrStr = '';
var newPasswordVal = $(".newPassword").val();
if(newPasswordVal.length < 6) newPasswordErrStr += "The password must be at least 6 characters";
document.getElementById("New_Password_error").innerHTML = newPasswordErrStr;
// VALIDATE EMAIL
var newEmailErrStr = '';
var newEmailVal = $(".newEmail").val();
if (newEmailVal === "") newEmailErrStr += "The email must not be left empty<br/>";
if (newEmailVal !== /^[a-zA-Z0-9]#[a-zA-Z])+.[a-z]/ ) newEmailErrStr += "The email must contain # symbol in it.";
document.getElementById("New_Email_error").innerHTML = newEmailErrStr;
});

How to allow non alphanumeric characters in a html5 / jquery mobile form input

I have a form input field for a to-do list style app for iOS using cordova. I'd like the user to be able to enter characters such as: ! % & +
However these caused the app to crash. My temporary fix was to restrict the key input on the form field using the .keypress function. However I'd like to find a way for users to be able to include these characters in their list items. (I also realized that adding a blank space as the only input causes the app to crash.)
I've see a lot of Q+As for validation that restricts the use of these characters but is it possible to be able to use them in a form input?
Thank you!
/* Form to make a new list item */
$('.formMain').submit(function () {
var key = Date.now();
var text = $('#todo').val();
var textTrim = text.replace(/ /g, '').toLowerCase();
var checked = false;
var quantity = $('#quantity').val();
// if the inputs are blank
if (text.length == 0) {
return false;
}
// if item already on list
else if ($('.list #' + textTrim).length) {
alert(text + " already on list!");
}
// if the input box is not empty run the template function
else if ((text.length > 0) === true) {
var html = template(text, textTrim, key, checked, quantity);
$('.list').append(html);
itemListArray.push({ key: key, text: text, textTrim:textTrim, checked: checked, quantity: quantity});
// Save the item list array
if (window.localStorage) {
window.localStorage.setItem('itemListArray', JSON.stringify(itemListArray));
}
$('#todo').val("");
$('#quantity').val("");
}
return false;
Thank you for the push in the right direction noahnu.
The crashes were occurring when meta-characters were being assigned to my "textTrim" variable. I believe the issue is when that variable contains meta-characters and is assigned to the ID of a html tag. (I'm using textTrim as a way to uniquely identify items for validation purposes).
var textTrim = escapeHtml(text).toLowerCase();
The problem was solved by creating a escapeHtml function that replaces each character with its decimal value. e.g.
function escapeHtml(text) {
return text
.replace(/&/g, "38") // etc

I would like to use JQuery to validate a form unsing .inArray() and .val()

The script below is suppose to insert a message using .insertAfter() if a user doesn't type in an # symbol within a field . This script also displays an error message if the user types in a value that matches a value from the invalidEmailAddresses array.
For some reason only the second part of this script executes.
If a user types in an # symbol they get a message but if the user types in an address similar to test#yahoo.com a message doesn't display. Not sure if i organized the code correctly.
$(document).ready(function(){
$("input[name='emailAddress']").blur(function(){
// Actual Email Validation function
var hasError = false;
var emailaddressVal = $("input[name='emailAddress']").val();
var invalidEmailAddresses =
['goddady.com', 'aol.com', 'yahoo.com', 'yahoo.fr'];
if ($.inArray(emailaddressVal,invalidEmailAddresses) > 0) {
$( "<span id='emailMessage'>The email provided is not from a business related domain. Please use an appropriate email address instead.</span>" ).insertAfter( "input[name='emailAddress']" );
} else {
$ ('#emailMessage').css('display','none');
}
if ($("input[name='emailAddress']").val().indexOf('#') > -1) {
$ ('#emailMessage').css('display','none');
}
else {
$( "<span id='emailMessage'>The email provided does not contain an # symbol</span>" ).insertAfter( "input[name='emailAddress']" );
}
if(hasError == true) { return false; }
});
});
This is working if you add the following code
$(document).ready(function() {
$("input[name='emailAddress']").blur(function() {
// Actual Email Validation function
$('#emailMessage').html("");
var hasError = false;
var emailaddressVal = $("input[name='emailAddress']").val().trim();
var invalidEmailAddresses = ['goddady.com', 'aol.com', 'yahoo.com', 'yahoo.fr'];
if (!isValidEmailAddres(emailaddressVal)) {
$("<span id='emailMessage'>The email provided does not contain an # symbol</span>").insertAfter("input[name='emailAddress']");
hasError = true;
} else {
debugger
emailaddressVal = emailaddressVal.split('#').slice(1)[0].trim();
if ($.inArray(emailaddressVal, invalidEmailAddresses) >= 0) {
$("<span id='emailMessage'>The email provided is not from a business related domain. Please use an appropriate email address instead.</span>").insertAfter("input[name='emailAddress']");
} else {
$('#emailMessage').css('display', 'none');
}
}
if (hasError == true) {
return false;
}
});
function isValidEmailAddres(emailID) {
var regexExp = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return regexExp.test(emailID);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input name="emailAddress" />
The issue lies with this if conditional: if ($.inArray(emailaddressVal,invalidEmailAddresses) > 0).
Since the $.inArray() method returns the index of a string found, when a value of 0 is returned, it is actually found—but at the start of the string (position 0, because JS is zero-based). So, you should use !== -1 instead, i.e.: if ($.inArray(emailaddressVal,invalidEmailAddresses) !== -1).
However, this does not completely solve your issue — $.inArray() only compares string, it does not search for it. Therefore if your string contains the blacklisted email domains, but does not match exactly, it will return false. In this case, you should use regular expression instead. The strategy is simple: use .each() to loop through your array, and take the value, use it to construct an expression which we will test your email address that is provided against.
Also, since there is the possibility that the user-entered email address fails both tests, two <div> of identical IDs will appear. This is invalid HTML. Instead, try using a class instead.
p/s: I also recommend changing listening to .blur() to .change() instead. It is more robust :)
With all the points above considered, I have refactored your code a little:
Declare a global (but still within function scope) error array called hasError. It will be used to store all error messages you get, since we cannot be sure if there will be one, or more than one error.
We construct two tests:
To test if email matches against blacklist using the string.search(regexp) method. If there is a match, the value returned will exceed -1. We then push the relevant error message into hasError in an object
To test if email contains the # sign, we use your default logic (which works beautifully). If there is an error, we push, again, the relevant error message into hasError in an object
At the end, we evaluate hasError. If it is not empty, then we know there is an error somewhere, and loop through it. The error messages are accessible via the messages keyword :)
Without further ado, here's your code:
$(document).ready(function() {
$("input[name='emailAddress']").change(function() {
// Actual Email Validation function
var hasError = [],
emailaddressVal = $("input[name='emailAddress']").val(),
invalidEmailAddresses = ['godaddy.com', 'aol.com', 'yahoo.com', 'yahoo.fr'];
// Check against blacklist
$.each(invalidEmailAddresses, function(i, v) {
var pattern = new RegExp(v, 'i');
if (emailaddressVal.search(pattern) > -1) {
hasError.push({
'test': 'blacklist',
'message': 'The email provided is not from a business related domain. Please use an appropriate email address instead.'
});
}
});
// Check if there is an '#' character
if ($("input[name='emailAddress']").val().indexOf('#') === -1) {
hasError.push({
'test': '# sign',
'message': 'The email provided does not contain an # symbol'
});
}
console.log(hasError);
// Error handling
$('#error').remove();
if(hasError.length > 0) {
var $error = $('<div id="error"><ul></ul></div>');
$.each(hasError, function(i,v) {
$error.find('ul').append('<li>'+v.message+'</li>');
});
$error.insertAfter("input[name='emailAddress']");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input name="emailAddress" type="email" />
</form>

Javascript to verify specific String from textbox

Here what the textbox result looks like,
Please add the following DNS entries
144.68.238.87 name.domain
144.68.238.88 name.domain
144.68.238.89 name.domain
The goal is to validate name.domain by making sure that the user replace name.domain to server name on textbox before submit it. If the user doesn't replace name.domain with their server name, then it will send alert message and return false until user replace it correctly.
Here is my codes,
function DomainValidate() {
var arrayOfLines = document.getElementById('txt').value.split('/n');
arrayOfLines.shift(); //use shift to skip the first line
for (i = 0; i < arrayOfLines.length; i++) {
//somewhere here need to split to get name.domain and then verify it
var domainName = arrayOfLines[i].split(" ", 2);
if(domainName.Equals("name.domain")
{
alert("You must replace name.domain to your new server name");
return false;
}
}
}
I am not sure if these are correct since I couldn't debug the javascript.
First issue I can see is that your character for the newline is incorrect. It should be \n not /n. Second issue I see is that i is a global variable, when it should be local. Third issue is that arrayOfLines[i].split(' ', 2); returns an array, but you are treating it like it returns a string on the next line if (domainName.Equals('name.domain').
With those corrections your code would look more like this:
function domainValidate() {
var arrayOfLines = document.getElementById('txt').value.split('\n');
arrayOfLines.shift(); //use shift to skip the first line
for (var i = 0; i < arrayOfLines.length; i++) {
var line = arrayOfLines[i].trim();
// Grab the second part of the split line, which represents the domain name
var parts = line.split(' ');
var domainName = parts[parts.length - 1];
if (!domainName || domainName === 'name.domain') {
alert("You must replace name.domain to your new server name");
return false;
}
}
}
As far as I can tell without testing, this should work as expected. The best way to test this though is with jsfiddle. Add your html and this script and call it to see if it produces the expected result.
Easiest way that I think
Suppose the id of textbox is domainTxt
src = document.getElementById("domainTxt");
if(verifyInput(src.value)){
//submit your form here
} else
{
return false;
}
function verifyInput(txtVal){
if(txtVal.indexOf("name.domain") >-1){
return false;
}else {
return true;
}
}

Extract substring out of a user input phone number using 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.

Categories

Resources