I want to check whether a regex field is empty or not and depending on that I want to execute a function.
the input field is a regex field and by default it stores "//" value in the field and I dont want to execute a function if the value contains "//" . Only when user enters some value I would wnat to execute the function.
new shared.form.RegexField({
ref : 'regexField',
fieldLabel : 'Regular Expression',
allowBlank : false,
width : 300,
});
Ex:
var rule = "//";
if(rule) {
// dont do anything;
}
however if rule contains some value like:
rule = "/test/";
if(rule) {
// call API sevrice.
}
is this possible?
if (rule.match("/\/\//")) {
// don't call because it's equal to "//"
} else {
// call API service
}
var rule = '//www.example.com'
if(rule.replace(/(\/\/)(?=(\S)*)/,'')){
// call API sevrice.
}else {
// dont do anything;
}
Related
I read the following post to understand how to use cookies to capture UTM URL Parameters:
https://jennamolby.com/how-to-use-cookies-to-capture-url-parameters/
I genuinely think that the code she outlined has all the write steps, but that it wont actually work. Getting this in Stackoverflow so that we can update the code and so that we can update the author so that others (like myself) do not have issues going forward.
Parse the URL
The URL parameters need to be parsed so the cookie values can be set. This can be done using javascript.
// Parse the URL
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
// Give the URL parameters variable names
var source = getParameterByName('utm_source');
var medium = getParameterByName('utm_medium');
var campaign = getParameterByName('utm_campaign');
Setting the Cookie Values
In order to set the cookie values, jQuery and the jQuery Cookie Plugin must be on the page.
<script src="https://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script src="/path/to/js.cookie.js"></script>
Using the variables defined in the first step, the cookie values can be set.
// Set the cookies
if($.cookie('utm_source') == null || $.cookie('utm_source') == "") {
$.cookie('utm_source', source);
}
if($.cookie('utm_medium') == null || $.cookie('utm_medium') == "") {
$.cookie('utm_medium', medium);
}
if($.cookie('utm_campaign') == null || $.cookie('utm_campaign') == "") {
$.cookie('utm_campaign', campaign);
}
Then we grab the cookie values and set the form field values
// Grab the cookie value and set the form field values
$(document).ready(function(){
$('input[name=utm_source').val(utm_source);
$('input[name=utm_medium').val(utm_medium);
$('input[name=utm_campaign').val(utm_campaign);
});
I have the following questions:
Does Jquery still support cookies?
I am confused about the below code. I do not think this will work, because it is not reading the cookie values.
// Grab the cookie value and set the form field values
$(document).ready(function(){
$('input[name=utm_source').val(utm_source);
$('input[name=utm_medium').val(utm_medium);
$('input[name=utm_campaign').val(utm_campaign);
});
Shouldn't the code be the following:
$(document).ready(function(){
/ Put the variable names into the hidden fields in the form.
$('input[name=utm_source]').val($.cookie('utm_source'));
$('input[name=utm_medium]').val($.cookie('utm_medium')_;
$('input[name=utm_campaign]').val($.cookie('utm_campaign'));
}
I have a regex for a set of use cases
Based on that regex I'm trying to prevent the user to type invalid formats.
The regex works and preventing the user adding invalid formats also works.
The part with which I'm struggling now is that if the default value is invalid, the user cannot add additional valid characters.
Here is what I have: http://jsfiddle.net/jgqco7by/2/.
<input id="myInput" type="text" value="co vi1d-" />
var previousValue = document.getElementById('myInput').value;
var pattern = /^[a-zA-Z]+(?:[ -][a-zA-Z]+)*([ ]|[-])?$/g;
function validateInput(event) {
event = event || window.event;
var newValue = event.target.value || '';
if (newValue.match(pattern)) {
// Valid input; update previousValue:
previousValue = newValue;
} else {
// Invalid input; reset field value:
event.target.value = previousValue;
}
}
document.getElementById('myInput').oninput = validateInput;
In this example since I have a default value which contains a number, which is not allowed, everything I type is replaced with previous value because the regex keeps coming back as invalid.
How could I build this so that, if the default value is invalid, the user can still add additional VALID values without having to remove the default invalid values first?
If you want to have the invalid data and a valid one in the same input I'm not seeing how it will happened with your approach.
If you want to have an initial value (that can be either valid or invalid) and then to append something (which is valid) then why are you checking for the initial state.
The third variant is to have both
Empty field and putting a valid chars only
Initial value (valid or invalid) and appending something (valid)
And the result will be to have a valid stuff.
Please place your question / requirement in a more structured manner.
As for the code I would suggest to change your regex. I can give suggestions for modification. :)
For the code:
<input id="myInput" type="text" value="co vi1d-" />
<p id="messageField"></p>
(function() {
const pattern = new RegExp(/^[a-zA-Z]+(?:[ -][a-zA-Z]+)*([ ]|[-])?$/g);
const messageField = document.getElementById('messageField');
function validateInput(event) {
var newValue = event.target.value; // no sense to have a check and to overwrite with window.event , its a different context
messageField.innerText = pattern.test(newValue) ? '' : 'incorrect input'; // its better to use test() method rather than match()
}
document.getElementById('myInput').oninput = validateInput;
}());
I want to set javascript variable with single quote. How it is possible. I am passing value to my function as parameter. and I am using this value to retrieve value of checkbox. So my problem is that if I am alerting value then it give me 'user' instead of 'sanjay' Here 'sanjay' is my value which is I am passing to parameter. And this will use to retrieve value of checkbox document.getElementById.
function single(user){
var abc = '\' user \'';
alert(abc);
return false;
var chksingle = document.getElementById(abc).checked;
alert(chksingle);
return false;
if (userlist() === false)
{
return false;
}
else
{
document.tallyexport.method = "post";
document.tallyexport.action = "checksingle.php";
document.tallyexport.submit();
}
}
Use string concatenation. The way you are doing it right now has user as part of the actual string, not using the variable.
var abc = "' " + user + " '"
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>
I am adding a Search feature, and if the user is on the search results and they refresh the page I want it to stay at that search. I already put the search query into the URL, but I don't know how to retrieve it. It will most likely require a regexp so anyone that is experienced with regexp, please help.
Here is how I put it into the URL:
function trimspace(str) {
str = str.replace(/ +(?= )/g, '');
return str;
}
function searchMail() {
var query = trimspace($('#search_input').val());
if (query == '' || !query || query == null) {
$('#search_input').focus();
}
else {
window.location.hash = '#!/search/' + query;
$('#loader').show();
$.get('tools.php?type=search', { q: query }, function(data, textStatus) {
$('#loader').hide();
if (textStatus == 'success') {
hideAllTabs();
$('#search_results').html(data).show();
document.title = "Search results - WeeBuild Mail";
}
else {
alertBox('Search failed. Please try again in a few minutes.', 2500);
}
});
}
}
And besides just retreiving the query I need to be able to detect if the hash is #!/search/query.
Thanks in advance!
Detect if query is #!/search/query:
location.hash==='#!/search/query'
Finding out about the query parts assuming the query is #!/search/query:
var parts = location.hash.split('/');
parts[0] is #!. parts[1] is search and parts[2] is test. Doing with the parts want you want should now be trivial enough.
In response to the comments:
function getPartAndRemainder(){
var parts = location.hash.split('/');
if(parts[0]!=='#!' || parts.length<2){
// Value after # does not follow the expected pattern #!/part/any_parameters
throw new Error('Cannot parse application part.');
}
return {
// Contains the part of your application (word after first slash after #)
part: parts[1],
// Contains everything after second slash after # or the empty string
remainder: location.hash.substring(
// Length of #! (or whatever somebody might use instead)
parts[0].length
// Length of first slash
+1
// Length of your application part's name
+parts[1].length
// Length of the second slash
+1)
};
}
The function gives back an object that contains the part of your application at the key part and the remainder key will contain the rest. So, if your URI would be something#!/search/test the function would return {part:'search', remainder:'test'}.
In case the URI can't be parsed, you'll get an error and you should then use a sensible default instead.
You would use the method as follows whenever the hash changes or at some other event (point in time) where you are interested in the hash value:
try {
var hashValue = getPartAndRemainder();
if(hashValue.part==='search'){
var query = hashValue.remainder;
alert('You searched: '+query)
}
if(hashValue.part==='inbox'){
alert('You are in inbox, now');
}
} catch(e){
// It was not possible to parse the value after the # from URI according to our expected pattern.
alert('No idea what to do with: '+location.hash);
}
This regex will match anything after the search param, is this what you are looking for?
/#1/search/(.*)/
var match = /\/.*\/.*\/(.*)\//i.exec(location.hash)
//match contain the query