I use Javascript below to call the Viber messenger chat for a specific phone number I paste into the field. How to change it that when inserting a number, unnecessary characters are removed: spaces, brackets, hyphens and only the last 10 digits of the number are left?
<input type="tel" id="tel" pattern=".{10}" maxlength="10" required />
<input type="button" id="btn-1" value="Viber" onClick="javascript: window.open('viber://chat?number=%2B38' + document.getElementById('tel').value, '_self');" />
Thanks.
You can use basic JS string functions:
(function() { // Do not allow using variables outside script
var tel = document.getElementById("tel");
tel.maxLength = 20; // When JS enabled, limit is more than 10
tel.pattern = ".*"; // When JS enabled, allow everything
tel.onchange = // After input
tel.onkeyup = // Key is up (after character written)
tel.onkeypress = // Character writen (for repeating)
function () {
var str = tel.value;
for (var str_old = null; str !== str_old;) { // Until no changes done
str_old = str;
str = str // You can put here more characters or regex
.replace("-", "") // Multiple similar characters
.replace("–", "")
.replace("—", "")
.replace("/", "")
.replace(" ", "")
.replace("(", "")
.replace(")", "")
.replace("[", "")
.replace("]", "")
.replace("{", "")
.replace("}", "");
}
tel.value = str.substr(-10); // Put it back and use last 10 characters (without '-' means except first 10 characters)
}
})()
<input type="tel" id="tel" maxlength="10" pattern="[^-–—/ ()[\]{}]+" required />
<input type="button" id="btn-1" value="Viber" onClick="javascript: window.open('viber://chat?number=%2B38' + document.getElementById('tel').value, '_self');" />
Related
I am having a problem with regular expression in javascript. What i am trying to do is a form register in which i must validate the first name so i decided to go with javascript validation (can you please tell me if going with js is the better option or going with ajax php reg validation?). So I wrote my code by checking some tutorials and reading from google but i am still having a problem. It is not working ! It runs on blur event using jquery so I need your help please to do this.
The pattern i am trying to check is for special characters in the user input
/[\'^£$%&*()}{##~?><>,|=_+]+$/g;
here is my script:
$(document).on('blur','.first_name_input', function() {
var firstNameInput = $(".first_name_input").val();
if (firstNameInput !== '') {
//var exp = /[a-zA-Z0-9-]+$/g;
var exp = /[\'^£$%&*()}{##~?><>,|=_+]+$/g;
//if (firstNameInput.test(/^[\'^£$%&*()}{##~?><>,|=_+-]+$/)) {
//if (firstNameInput.match(/[a-zA-Z0-9]*/g)) {
if (firstNameInput.match(exp)) {
var firstnameValidity = "<div class='name_not_valid_div'>× Not allowed characters present!</div>";
$('body').prepend(firstnameValidity);
$(".name_not_valid_div").hide().fadeIn('slow');
if (!errorArray.includes("firstName")){
errorArray.push("firstName");
}
} else {
$(".name_not_valid_div").hide();
if (errorArray.includes("firstName")){
for(var i = errorArray.length - 1; i >= 0; i--) {
if(errorArray[i] === "firstName") {
errorArray.splice(i, 1);
}
}
}
}
}
});
and my html code is :
<tr>
<td class="label">First Name: </td>
<td class="input"><input type="text" name="first_name" class="input_bar first_name_input" size="30" Placeholder="First Name" /><br/></td>
</tr>
1st: use .trim() to avoid left/right whitespaces or even the spaces without any characters $(".first_name_input").val().trim();
2nd: for validation
// if the string has special characters
function string_has_spec_char(str){
var reg = /[~`!##$%\^&*+=\-\[\]\\';,_./{}\(\)\|\\":<>\?]/g;
return reg.test(str);
}
// check if string has spaces
function string_has_spaces(str) {
var reg = /\s/g;
return reg.test(str);
}
and use it like
if(string_has_spec_char(firstNameInput) === false){
// the first name doesn't have special characters
}
if(string_has_spaces(firstNameInput) === false){
// the first name doesn't have spaces
}
I am validating user input where it should accept only 6 digits or OB followed by 8 digits only.
It works very fine for digits but when I enter any alphabet (other than O) for first time it shows "undefined" in the input text box. How to overcome this? I have initialize all variables and tried changing regular expression(/[OB0-9]*/) also but nothing is working.
Here is my jsp code with RegEx:
<input type="text" value="<c:out value='${bookingPathView.extraAANumber}'/>" name="businessExtrAA" id="enterPassengerDetailsForm.businessExtrAA" size="17" maxlength="10" pattern="[OB0-9]*" class="forceWidth-phone forceWidth6" />
Here is my Javascript code
var keepBusinessExtraMaxLength = function () {
var input = [];
jQuery("#enterPassengerDetailsForm\\.businessExtrAA").each(function(i) {
input[i]=this.defaultValue;
jQuery(this).data("idx",i);
});
jQuery("#enterPassengerDetailsForm\\.businessExtrAA").on("keyup", function (e) {
var field = jQuery(this);
var val=this.value;
var maxLength=isNaN(jQuery(field).val()) ? Number(jQuery(field).attr("maxlength")) : 6;
var thisIndex=jQuery(field).data("idx");
if (this.validity && this.validity.badInput || jQuery(field).is(":invalid") ) {
this.value = input[jQuery(thisIndex)];
return;
}
if (val.length > maxLength) {
val=val.slice(0, maxLength);
jQuery(field).val(val);
}
input[jQuery(thisIndex)]=val;
});
}
Your Regex seems to be matching only the characters , O, B and other numbers...
To make it match
6 digits or OB followed by 8 digits only
You can use this regex: ^(?:[0-9]{6}|OB[0-9]{8})$
Demonstration: http://www.regexpal.com/?fam=96586
I am writing code to convert numbers counted in thousands (separated in writing in chunks of 3) into myriads (separated in writing in chunks of 4) for Japanese formatting.
the current code produces following results:
ex)
input: 123,456,789,123,456
output: 123兆4567億8912万3456
Using regular expressions I have been able to delete sequences of four 0's and the proceding character with myriad = myriad.replace(/0000\D/g, "");
result:
input: 12,300,002,345
output: 123億2345 (0000万 was deleted)
However, the code currently doesn't delete unnessecary zero's:
ex)
input: 32,131,200,232,132
output: 32兆1312億0023万2132
(I would like to delete the two zeros before 23万)
I am trying to find a regex solution to this and have attempted with myriad = myriad.replace(/?=0{1,3}/g, ""); to no avail... I am rather stumped, any suggestions would be helpful
EDIT:
I think the regex should replace 0's that follow any \D , but I can't figure out how to delete them without deleting the preceding character as well
EDIT: working app:
<!DOCTYPE html>
<html>
<head>
<title>変換天才</title>
<script>
//myriad converter function help from Stack Overflow user paxdiablo
function makeNum(num) {
num = num.replace(/,/g,""); //remove commas
var markers = "万億兆京該秭穣溝澗正載極";
var result = "";
//regroup in myriads
while (num.length > 4) {
if (markers.length == 0) {
result = "(?)" + num.substr(num.length-4) + result;
} else {
result = markers.substr(0, 1) + num.substr(num.length-4) + result;
markers = markers.substr(1);
}
num = num.substr(0, num.length-4);
}
return num + result;
}
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
// insert commas for readability
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
function makeCom(num){
num = num.replace(/,/g, "");
var result = num.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
return result;
}
function convert(){
var innum = document.getElementById("input").value;
var parsnum = (innum.replace(/,/g,""));
if (isNaN(parseInt(parsnum)) == true) {
document.getElementById("converted").innerHTML = "Please enter valid number.";
}
else {
var myriad = makeNum(innum);
// delete unnec. zeros
myriad = myriad.replace(/0000\D/g, "");
myriad = myriad.replace(/(\D)0+/g, "$1");
document.getElementById("converted").innerHTML = myriad ;
//display number with commas
var commanum = makeCom(innum);
document.getElementById("commaed").innerHTML = "You entered: " + commanum ;
}
}
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
// button functions
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
function multiplier(kake) {
var mult = document.getElementById("input").value;
if (mult == "") {
mult = kake;
}
else if (isNaN(mult)==false){
mult = (mult * kake);
}
else {
document.getElementById("converted").innerHTML = "Please enter valid number";
return;
}
document.getElementById("input").value = mult;
}
function thou(){
multiplier(1000);
}
function xMil(){
multiplier(1000000);
}
function xBil(){
multiplier(1000000000);
}
function xTril(){
multiplier(1000000000000);
}
function xQuad(){
multiplier(1000000000000000);
}
function clr(){
document.getElementById("input").value = "";
document.getElementById("converted").innerHTML = "";
}
</script>
</head>
<body>
<div><p>Enter a large whole number (commas OK). </p></div>
<input type="text" id="input"/>
<input type="submit" id="submit" value="Convert" onclick="convert()">
<br>
<input type="button" id="xthou" onclick="thou()" value="thousand">
<input type="button" id="xmil" onclick="xMil()" value="million">
<input type="button" id="xbil" onclick="xBil()" value="billion">
<br>
<input type="button" id="xtril" onclick="xTril()" value="trillion">
<input type="button" id="xquad" onclick="xQuad()" value="quadrillion">
<input type="button" id="clr" onclick="clr()" value="Clr">
<br><br>
<div><span id="commaed"></span></div>
<br>
<div id="converted"></div>
</body>
</html>
You need to use capturing group.
string.replace(/(\D)0+/g, "$1")
(\D) captures a non-digit character and the following 0+ would match one or more 0's. Replacing the matched chars with the chars present inside the group index 1 will give you the desired output.
I find regex fiddles very helpful for this kind of thing. I made one here:
https://regex101.com/r/jG3aB5/1
I think the regex that will solve your problem is this one:
(?:[^0-9])*(0*)
It matches an arbitrary number of zeros that follow a single non-digit character. The non-digit character is not captured and will not be replaced.
Another approach: Use lookbehind to not include the match character \D but match only zeros. Please see the working DEMO
/(?!\D)0+/g
In your case:
myriad = myriad.replace(/(?!\D)0+/g, "");
I have a straight forward classic ASP page that uses a where the user can enter any standard keyboard key plus the Enter key (and even special ALT nnn values if they so desire)
My clarification is that I need to display an accurate character count back to the user on each ONKEYUP. So I need to know if the ENTER key has been pressed (/n) which needs to be counted as 2 chars as well as 8 other chars such as Tilde, Caret Left curly bracket, etc. which also count as 2 characters. Finally I need to validate each ONKEYUP char to ensure that they will be valid SMS chars, if not they need to be replaced in the TextArea with and Underscore (account as 1 char only)
So what I need to do is to be able to validate each character on the ONKEYUP remembering that a char could be inserted anywhere in the TextArea, an existing char could be deleted from the TextArea or parts of or the entire text could be pasted at any time
The current HTML code is as follows:
Enter your message - Characters left
<input type="text" name="chl" value="<%=Cclen%>" size=3 diabled readonly>
<br />
<textarea id="SMSmsg" name="SMSmessage" MAXLENGTH="600" rows=5 cols=35 onKeyUp="textCounter
(this)"></textarea>
<input type="text" name="chl" value="<%=Cclen%>" size=3 diabled readonly>
<br />
<textarea id="SMSmsg" name="SMSmessage" MAXLENGTH="600" rows=5 cols=35 onKeyUp="textCounter
(this)"></textarea>
The JavaScript function testcounter is as follows:
function textCounter() {
var extra = 0;
var nextra = 0;
var msgLength = 160 - (document.gs.SMSmessage.value).length - (document.gs.SMSbot.value).length;
var index = document.gs.SMSmessage.value.indexOf('\n');
while (index != -1) {
extra += 1;
index = document.gs.SMSmessage.value.indexOf('\n', index + 1);
}
Canam = nameCounter()
if (document.gs.SMSrequest.value == 'eml') {
extra = 0
nextra = 0
chnl = 999
} else {
if (document.gs.chnl.value > 0) {
nextra = 3
}
}
document.gs.chl.value = msgLength + extra - nextra;
Camsg = textWarning();
}
function nameCounter() {
var botLength = (document.gs.SMSbot.value).length;
document.gs.chnl.value = botLength;
}
function textWarning() {
var Ccwarn = " ";
if (document.gs.chl.value < -299) {
Ccwarn = "** Error ** - Extended text too long"
} else {
if (document.gs.chl.value < 0) {
if (document.gs.chex.value == 'N') {
Ccwarn = "** Error ** - Standard text too long"
} else {
Ccwarn = "** Warning ** - Extended text - Additional charge applied"
}
}
}
document.gs.chw.value = Ccwarn;
}
Any suggestions as to how to recode the JS function much appreciated taking into account my comments on the user actions within the TextArea
i am trying to learn html and javascript. I have created an html form and am using javascript to validate the fields. I have a isNaN check for the age field, a regex check for emial and a presence check for all fields. I am currently outputting the form to the address bar but this does not work as i am getting errors.
<title> </title>
<script type="text/javascript">
function validate()
{
var errors = 0;
if (isNumeric(document.getElementById("age").value) == false)
{
errors++;
}
if (emailCheck(document.getElementById("email").value) == false)
{
errors++;
}
var inputBoxes = document.getElementsByTagName('input');
for(var i= 0; i < inputBoxes.length; i++)
{
if(inputBoxes[i].type != 'text') continue;
if(presenceCheck(inputBoxes[i].value) == false)
{
errors++;
}
}
console.log(errors);
if(errors == 0)
{
window.location.assign("output.html#" + "%%" + "name" + "%%" +
document.getElementById("name").value + "%%" + "email" + "%%" +
document.getElementById("email").value + "%%" + "age" + "%%" +
document.getElementById("age").value + "%%" + "comments" + "%%" +
document.getElementById("comments").value);
}
}
function isNumeric(number)
{
return !isNaN(number) && number != null && number != "";
}
function emailCheck(email)
{
var emailRegex = /\s+#\s+.\s+/;
return emailRegex.test(email);
}
function presenceCheck(data)
{
var regex = /\s+/;
return regex.test(data);
}
</script>
Below is the form which is just incased in body tags at the moment
<form id="frmA" name="frmA">
<label name="frmName">Name:</label><br />
<input form="frmA" type="text" name="frmName" id="name"/><br />
<label name="frmEmail">E-Mail:</label><br />
<input form="frmA" type="text" name="frmEmail" id="email"/><br />
<label name="age">Age:</label><br />
<input form="frmA" name="frmAge" id="age"/><br />
<label name="frmComments">Comments:</label><br />
<textarea form="frmA" cols="50" rows="10" id="comments"></textarea><br />
</form>
<button onClick="validate();">Submit</button>
i know that the checks work when no data is present however when i input data in the form and hit submit i am still faced with 4 errors. (there are 5 errors with no data: 3x presence checks, 1 for the regex and one for the isNaN)
My question therefore is why am i still getting errors and why do i get no output.
Any help would be greatly appreciated.
Extra: i would also like the input fields to change colour when there is an error.
Your regexes are wrong. You have /\s+#\s+.\s+/ and it should be /\w+#\w+\.\w+/. You didn't escape the dot and \s matches whitespace, not strings. \w matches word. For a proper email regex you would need much more than that but for your simple case to work this will suffice. The second regex should be /\w+/.