I'm trying to validate a form field for MAC Addresses.
I've got this which works.
$('body').on('keyup', '#macAddess', function(e){
var e = $(this).val();
var r = /([a-f0-9]{2})([a-f0-9]{2})/i,
str = e.replace(/[^a-f0-9]/ig, "");
while (r.test(str)) {
str = str.replace(r, '$1' + ':' + '$2');
}
e = str.slice(0, 17);
$(this).val(e)
});
As the user is typing it's formatting the MAC Address, adding : after every pair of characters. It will only allow a-f and 0-9 so no invalid characters are being added.
I'd like to expand on it a little.. As the user is entering the MAC address I want a class adding to input showing it is wrong, until a fully formed MAC address is entered.
eg:
if (MAC is invalid) $('#' + id).addClass('badMac')
So if the user is entering a value the class will be added and only removed when a fully formed and valid mac is entered.
I'd like to keep in all with in the on('keyup') function.
How do I test if it is invalid and then set the class ?
You can test it with a regular expression that checks if the MAC address is valid:
var regexp = /^(([A-Fa-f0-9]{2}[:]){5}[A-Fa-f0-9]{2}[,]?)+$/i;
var mac_address = $(this).val();
if(regexp.test(mac_address)) {
//valid!
} else {
//invalid!
}
Note that if you write this on keyup event, you'll obtain the invalid statement till the user writes a whole valid MAC address.
Edit
Snippet working:
var regexp = /^(([A-Fa-f0-9]{2}[:]){5}[A-Fa-f0-9]{2}[,]?)+$/i;
var mac_address = "fa:09:91:d5:e4:5a";
if(regexp.test(mac_address)) {
console.log("Valid: "+ mac_address);
} else {
console.log("Invalid: "+ mac_address);
}
So try this code:
$('body').on('keyup', '#macAddess', function(e){
var e = $(this).val();
var r = /([a-f0-9]{2})([a-f0-9]{2})/i,
str = e.replace(/[^a-f0-9]/ig, "");
while (r.test(str)) {
str = str.replace(r, '$1' + ':' + '$2');
}
e = str.slice(0, 17);
$(this).val(e);
var regexp = /^(([A-Fa-f0-9]{2}[:]){5}[A-Fa-f0-9]{2}[,]?)+$/i;
var mac_address = $(this).val();
if(regexp.test(mac_address)) {
//valid!
} else {
//invalid!
}
});
function isValidMac(mystring){
var regex = /^([0-9A-F]{2}[:-]){5}([0-9A-F]{2})$/;
return regex.test(mystring);
}
$('body').on('keyup', '#macAddress', function(e){
var e = $(this).val();
var r = /([a-f0-9]{2})([a-f0-9]{2})/i,
str = e.replace(/[^a-f0-9]/ig, "");
while (r.test(str)) {
str = str.replace(r, '$1' + ':' + '$2');
}
e = str.slice(0, 17);
$(this).val(e)
$("#macAddress").toggleClass("badMac",!isValidMac(e));
});
input.badMac {
background-color : red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="macAddress">
I recommend you to use input event, which will also handle use cases when user uses Ctrl+C, Ctrl+V to input the MAC address, also together with the validation the code should look like this:
$(function() {
var regexp = /^(([A-Fa-f0-9]{2}[:]){5}[A-Fa-f0-9]{2}?)+$/i;
$("#macAddess").on("input", function(e) {
var tb = $(this);
var val = tb.val().replace(/[^a-f0-9]/ig, "");
var r = /([a-f0-9]{2})([a-f0-9]{2})/i;
while (r.test(val)) {
val = val.replace(r, '$1' + ':' + '$2');
}
val = val.slice(0, 17);
tb.val(val);
tb.toggleClass("badMac", !regexp.test(tb.val()));
});
});
.badMac {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="macAddess" />
You can use jQuery´s toggleClass() with a bool value. In this case with the return value of your regex test.
$('body').on('keyup', '#macAddess', function(e){
var input = $(this).val();
var regexp = /^(([A-Fa-f0-9]{2}[:]){5}[A-Fa-f0-9]{2}[,]?)+$/i;
$("#your-input-id").toggleClass("valid", regexp.test(input));
});
Related
I have a script I'm trying to write which takes a string and finds the dmcode then sends it to a function to format it correctly then returns the value. This seems to work but I can't get the replace function to work on the string calling it. This has got to be easy but everything I've tried has resulted in errors.
Your help is appreciated.
Max
function scrubDMC(DM){
var dmcode = DM;
for (var i = 0; i < dmcode.length; i++) {
DMC = dmcode[i];
match = DMC.match(/modelIdentCode="(.*?)"/im);
if (match !== null) {
var modelIdentCode = match[1];
}
match = DMC.match(/systemDiffCode="(.*?)"/im);
if (match !== null) {
var systemDiffCode = match[1];
}
match = DMC.match(/\ssubSystemCode="(.*?)"/im);
if (match !== null) {
var subSystemCode = match[1];
}
match = DMC.match(/subSubSystemCode="(.*?)"/im);
if (match !== null) {
var subSubSystemCode = match[1];
}
}
var sFileName = "DMC-" + modelIdentCode +"-"+ systemDiffCode +"-"+ systemCode + "-" + subSystemCode + subSubSystemCode + "-" + assyCode +"-"+ disassyCode + disassyCodeVariant +"-" + infoCode +infoCodeVariant +"-" +itemLocationCode;
console.log("sFileName : " + sFileName);
return sFileName;
}
Code calling the function that isn't working
var readyWarn2 = readyWarn.replace(/<symbol infoEntityIdent=".*?"\/>/ig, "");
var dmcode = readyWarn2.match(/<dmcode.*?>/ig);
scrubDMC(dmcode);
readyWarn2.replace(dmcode, sFileName);
Your last line needs to be
readyWarn2 = readyWarn2.replace(dmcode, sFileName);
Javascript strings can't be changed, so String.replace() returns a new string value.
I am trying to perform exact match of the text keyed in a textbox but, somehow it is working as partial match. I tried different options but could not figure out the cause.
RegExp.escape = function (text) {
//escape the +,[,?... characters
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
var resultLbl = $('#ResultLbl');
$('#SearchTxtBox').bind('change keyup', function () {
resultLbl.text('');
var options = [];
options.push('[1]My]');
options.push('[2]My Name]');
options.push('[3]Name]');
options.push('[2]My Name]');
var searchStr = RegExp.escape($.trim($(this).val()));
var searchArr = [];
if (searchStr != '' && searchStr != null) {
searchStr = searchStr.replace(/\,/g, '\\ ')
searchArr = searchStr.split('\\ ');
}
var search = searchArr[0];
search = search.replace(/[.?*+^$[\]\\(){}|-]/g, '');
var regex = new RegExp($.trim(search), 'gi');
$.each(options, function (i, option) {
if (option.match(regex) !== null) {
resultLbl.append(option + ' ');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Search:
<input type="text" id="SearchTxtBox"/>
<br/>
<label id='ResultLbl'></label>
Expectation:
If you key in the text 'Name' in textbox, only '[3]Name' should be
matched.
If you key in the text 'My Name' in textbox, only '[2]My
Name' should be matched.
Any suggestions are appreciated.
Instead of complex pre-processing, you can just test if the string matches this pattern:
^\[\d+\]<searchStr>\]$
with
var regex = new RegExp("^\\[\\d+\\]" + $.trim(searchStr) + "\\]$", 'gi');
Here is an updated snippet:
RegExp.escape = function (text) {
//escape the +,[,?... characters
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
var resultLbl = $('#ResultLbl');
$('#SearchTxtBox').bind('change keyup', function () {
resultLbl.text('');
var options = [];
options.push('[1]My]');
options.push('[2]My Name]');
options.push('[3]Name]');
options.push('[2]My Name]');
var searchStr = RegExp.escape($.trim($(this).val()));
var regex = new RegExp("^\\[\\d+\\]" + $.trim(searchStr) + "\\]$", 'gi');
$.each(options, function (i, option) {
if (option.match(regex) !== null) {
resultLbl.append(option + ' ');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Search:
<input type="text" id="SearchTxtBox"/>
<br/>
<label id='ResultLbl'></label>
I have phone numbers on my website that are automatically inserted via a JavaScript to display either a default phone number (that's defined within the primary JavaScript) or change to a variable phone number if the webpage is accessed by a URL string with the phone number in it - for example:
http:www.website.com?tfid=8005551212
What I need to do is make the phone numbers clickable for mobile users so that whichever phone number appears they can click it and it will call the phone number.
I understand that if you wrap the phone number with an anchor with the tel: attribute it will launch the click-to-call function, but how can the tag be written so it will allow for the phone number variable to be passed? ex:
variable telephone number
Do you mean this?
Please rewrite your script to not use document.write. If you ever call one of your functions after the page loaded it will wipe the page.
document.getElementById("phonenumber").innerHTML=''+phone_number+'';
Like this, using your original code
<div id="phonenumber">Call: </div>
function getPhone() {
var phone = get_named_cookie("MM_TrackableNumber");
if (phone == null) phone = "8885551313";
return formatnumber(phone);
}
window.onload=function() {
document.getElementById("phonenumber").innerHTML+=getPhone();
}
Full code
function pixelfire(debug) {
var phone_number = getVar("phone_number");
var keyword = getVar("keyword");
var source = getVar("source");
if (keyword) {
setcookie(keyword, phone_number);
} else {
var keyword = get_named_cookie("MM_Keyword");
var phone_number = get_named_cookie("MM_TrackableNumber");
return keyword || null;
}
var campaign = getVar("campaign");
var content = getVar("content");
var url = "http://www.mongoosemetrics.com/pixelfire.php?phone_number=" + phone_number;
var url = url + "&keyword=" + keyword;
var url = url + "&source=" + source;
var url = url + "&campaign=" + campaign;
var url = url + "&content=" + content;
myImage = new Image();
myImage.src = url;
}
function setcookie(key, tn, path) {
index = -1;
var today = new Date();
today.setTime(today.getTime());
var cookie_expire_date = new Date(today.getTime() + (365 * 86400000));
document.cookie = "MM_TrackableNumber=" + tn + ";path=/;expires=" + cookie_expire_date.toGMTString();
document.cookie = "MM_Keyword=" + key + ";path=/;expires=" + cookie_expire_date.toGMTString();
}
function getPhone() {
var phone = get_named_cookie("MM_TrackableNumber");
if (phone == null) phone = "8885551313";
return formatnumber(phone);
}
function get_named_cookie(name) {
if (document.cookie) {
index = document.cookie.indexOf(name);
if (index != -1) {
namestart = (document.cookie.indexOf("=", index) + 1);
nameend = document.cookie.indexOf(";", index);
if (nameend == -1) {
nameend = document.cookie.length;
}
var ret_one = document.cookie.substring(namestart, nameend);
return ret_one;
}
}
}
//function to format the phonenumber to (123) 456-7890
function formatnumber(num) {
_return = "1-";
var ini = num.substring(0, 3);
_return += ini + "-";
var st = num.substring(3, 6);
_return += st + "-";
var end = num.substring(6, 10);
_return += end;
return _return;
}
function getVar(name) {
get_string = document.location.search;
return_value = '';
do { //This loop is made to catch all instances of any get variable.
name_index = get_string.indexOf(name + '=');
if (name_index != -1) {
get_string = get_string.substr(name_index + name.length + 1, get_string.length - name_index);
end_of_value = get_string.indexOf('&');
if (end_of_value != -1) value = get_string.substr(0, end_of_value);
else value = get_string;
if (return_value == '' || value == '') return_value += value;
else return_value += ', ' + value;
}
} while (name_index != -1)
//Restores all the blank spaces.
space = return_value.indexOf('+');
while (space != -1) {
return_value = return_value.substr(0, space) + ' ' + return_value.substr(space + 1, return_value.length);
space = return_value.indexOf('+');
}
return (return_value);
}
window.onload = function () {
key = getVar("keyword");
tn = getVar("tfid");
source = getVar("source");
content = getVar("content");
campaign = getVar("campaign");
if (tn != "") {
setcookie(key, tn);
}
var phone_number = getPhone();
document.getElementById("phonenumber").innerHTML+=''+phone_number+'';
}
Like
?a=1&b=2&c=3
I only want to change b=6 while keep the other things the same, how to do it?
Following function if you have to replace any b=XXX with b=newBValue
function ReplaceB(strQuery,newBValue)
{
var idxStart= strQuery.indexOf("b=")
if(idxStart<0)
return; // b= not found, nothing to change
var idxFin=strQuery.substr(0,idxStart).indexOf("&");
var newQuery;
if(idxFin<0)
newQuery = strQuery.substr(0,idxStart) + "b="+newBValue
else
newQuery = strQuery.substr(0,idxStart) + "b="+newBValue+strQuery.substr(idxStart+idxFin)
return newQuery;
}
here a small function to do this:
jQuery.replaceURLParam = function (oldURL, replaceParam, newVal) {
var iStart = oldURL .indexOf(replaceParam + '=');
var iEnd = oldURL .substring(iStart + 1).indexOf('&');
var sEnd = oldURL .substring(iStart + iEnd + 1);
var sStart = oldURL .substring(0, iStart);
var newURl = sStart + replaceParam + '=' + newVal;
if (iEnd > 0) {
newURl += sEnd;
}
return newURl;
}
document.body.innerHTML = jQuery.replaceURLParam('www.foo.com?a=1&b=2&c=3', 'b', 6) ;
demo: http://jsfiddle.net/3rkrn/
var queryStr = "?a=1&b=2&c=3";
var startTag = "b=";
var endTag = "&";
var index1 = queryStr.indexOf(startTag) + startTag.length;
var index2 = queryStr.indexOf(endTag,index1);
var newValue = 23;
queryStr = queryStr.substr(0, index1) + newValue + queryStr.substr(index2);
alert(queryStr);
See it here : http://jsfiddle.net/aQL8p/
var test = "?a=1&b=2&c=3".replace(/b=2/gi,"b=6");
alert(test);
Example
var test = "?a=1&b=2&c=3".replace("b=2","b=6");
alert(test);
Example
var test = "?a=1&b=2&c=3".split("b=2").join("b=6");
alert(test);
Example
Regardless of Number
Want to change to value of b regardless of number it is already? Use:
var test = "?a=1&b=2&c=3".replace(/b=\d/gi, "b=6");
alert(test);
Example
var queryString = '?a=1&b=2&c=3'.replace(/([?&;])b=2([$&;])/g, '$1b=6$2');
jsFiddle.
(JavaScript regex does not support lookbehinds).
See if this works for you - a more or less universal urlFor:
https://gist.github.com/4108452
You would simply do
newUrl = urlFor(oldUrl, {b:6});
post.php?replyto=username&othervariable=value
For example, if I click a link with this url, then I want to take the replyto=username value and insert the value in a textbox using jquery.
function insertParamIntoField(url, param, field) {
var anchor = document.createElement('a'), query;
anchor.value = url;
query = anchor.query.split('&');
for(var i = 0, kv; i < query.length; i++) {
kv = query[i].split('=', 2);
if (kv[0] == param) {
field.value = kv[1];
return;
}
}
}
$("a .reply").click(function () {
insertParamIntoField(this.href, "replyto", $("input .inputField")[0]);
return false; // prevent default action
});
this is my html code:
<textarea name="inputField" id="inputField" tabindex="1" rows="2" cols="40"></textarea>
<a class ="reply" href="home.php?replyto=username">reply</a>
function insertParamIntoField(url, param, field) {
var anchor = document.createElement('a'), query;
anchor.href = url;
query = anchor.search.substring(1, anchor.search.length).split('&');
for(var i = 0, kv; i < query.length; i++) {
kv = query[i].split('=', 2); console.log(kv);
if (kv[0] == param) {
field.value = kv[1];
return;
}
}
}
$("a.reply").click(function () {
insertParamIntoField(this.href, "replyto", $("textarea.inputField")[0]);
return false; // prevent default action
});
The insertParamIntoField function will work for any well formed URL (as a string). It works by creating a new anchor DOMElement (but never attaches it to the dom) for that URL and then by using the built in properties of anchor elements (query, hash, etc.) to extract what we want.
If the URL is from an anchor element, we can create a new version of this function that uses that existing anchor rather than creating a new one:
function insertParamIntoField(anchor, param, field) {
var query = anchor.search.substring(1, anchor.search.length).split('&'); // anchor is a DOMElement
for(var i = 0, kv; i < query.length; i++) {
kv = query[i].split('=', 2);
if (kv[0] == param) {
field.value = kv[1];
return;
}
}
}
$("a.reply").click(function () {
insertParamIntoField(this, "replyto", $("textarea.inputField")[0]);
return false; // prevent default action
});
Parsing the URL can be done with a simple function. Use this in your Javascript:
$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
return results[1] || 0;
}
You can then call:
$.urlParam('username');
and it will return the user name. So, to actually use it with your text box, do:
$('#textBoxId').val($.urlParam('username'));
$('textarea').val("<?php echo $_GET['replyto']");
Using the code from this SO answer (which is great btw) by Artem Barger to get any parameter by name from the query string you could do:
function getParameterByName( name )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if(results == null )
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
Then just insert the value into the textbox:
$("#yourTextBox").val(getParameterByName('replyto'));
You should be able to grab the ?replyto=username&othervariable=value part with window.location.search, then you have to get the part you want
var print = '?replyto=username&othervariable=value'; // Would be window.location.search in practice
$('textBox').val(print.substr(print.indexOf('replyto=')+8,print.indexOf('&')-(print.indexOf('replyto=')+8)));
Here is some Javascript that should help you. Just take the return value from the getQuerystringNameValue() function and use $("#textboxID").val(returnValue); to assign it to the textbox.
alert("name1" + " = " + getQuerystringNameValue("name1"));
alert("name2" + " = " + getQuerystringNameValue("name2"));
alert("name3" + " = " + getQuerystringNameValue("name3"));
function getQuerystringNameValue(name)
{
// For example... passing a name parameter of "name1" will return a value of "100", etc.
// page.htm?name1=100&name2=101&name3=102
var winURL = window.location.href;
var queryStringArray = winURL.split("?");
var queryStringParamArray = queryStringArray[1].split("&");
var nameValue = null;
for ( var i=0; i<queryStringParamArray.length; i++ )
{
queryStringNameValueArray = queryStringParamArray[i].split("=");
if ( name == queryStringNameValueArray[0] )
{
nameValue = queryStringNameValueArray[1];
}
}
return nameValue;
}