regex with urls - javascript

I check if a given url matches another one (which can have wildcards).
E.g. I have the following url:
john.doe.de/foo
I'd now like to check whether the url is valid or not, the user defines the string to check with, e.g:
*.doe.de/*
That works fine, but with the following it should NOT work but it gets accepted:
*.doe.de
Here the function i wrote till now, the urls are stored as firefox prefs and i the "checkedLocationsArray" containts all urls to be checked.
function checkURLS(index)
{
if(index >= 0)
{
var pos = getPos("URL-Mask");
var url = tables[index][pos];
if(url != null && url != "")
{
var urlnow = "";
if(redlist_pref.prefHasUserValue("table.1"))
{
var checkedLocationsArray = new Array();
for(i = 0; i < tables.length; i++)
{
checkedLocationsArray[i] = tables[i][pos];
}
for(i=0;i<checkedLocationsArray.length;i++)
{
urlnow = checkedLocationsArray[i];
if(urlnow == url)
{
return true;
}
if(urlnow.indexOf('*.') != -1)
{
while(urlnow.indexOf("*.") != -1)
urlnow = urlnow.replace("\*.", "\.[^\.]*");
}
if(urlnow.indexOf('.*') != -1)
{
while(urlnow.indexOf(".*") != -1)
urlnow = urlnow.replace(".\*", "([^\.]*\.)");
}
if(urlnow.indexOf('/*') != -1)
{
while(urlnow.indexOf("/*") != -1)
urlnow = urlnow.replace("/*", /\S\+*/)
}
else if(url.lastIndexOf('/') != -1)
{
return false;
}
var regex = new RegExp(urlnow);
var Erg = regex.exec(url);
if(Erg != null)
return true;
}
}
return false;
}
}
}
i think the "else if(url.indexOf('/') != -1)" is the important part. It should work just fine like that, if I alert it I even get that the result is true but it seems like the if is not being executed..
If anything is unclear, please just post a comment. Thanks in advance!

Why don't you just add the characters for beginning and end of string?
function checkURLS(index)
{
if(index >= 0)
{
var pos = getPos("URL-Mask");
var url = tables[index][pos];
if(url != null && url != "")
{
var urlnow = "";
if(redlist_pref.prefHasUserValue("table.1"))
{
var checkedLocationsArray = new Array();
for(i = 0; i < tables.length; i++)
{
checkedLocationsArray[i] = tables[i][pos];
}
for(i=0;i<checkedLocationsArray.length;i++)
{
urlnow = checkedLocationsArray[i];
if(urlnow == url)
{
return true;
}
//Check there's nothing else in the string
urlnow = '^' + urlnow + '$';
if(urlnow.indexOf('*') != -1)
{
while(urlnow.indexOf("*") != -1)
urlnow = urlnow.replace("\*", ".*");
}
else if(urlnow.lastIndexOf('/') != -1)
{
return false;
}
var regex = new RegExp(urlnow);
var Erg = regex.exec(url);
if(Erg != null)
return true;
}
}
return false;
}
}
}

The problem seems that you don't check for the start and the end of the string. Change your code to something like
urlnow = '^'+urlnow+'$'; // this is new
var regex = new RegExp(urlnow);
^ is the RegExp code for string-start and $ the code for string-end. That way you ensure that the whole url has to match the pattern and not only a part of it.

I figured out that I did the url was not the current url, I changed that below.
I also changed that the * are now replaced with a regular expression and the dots have to be there in this situation.
function redlist_checkURLS(index)
{
if(index >= 0)
{
var pos = getPos("URL-Mask");
var url = currenturl.replace("http://", "");
if(url != null && url != "")
{
var urlnow = "";
if(pref.prefHasUserValue("table.1"))
{
var urlsok = 0;
var checkedLocationsArray = new Array();
for(i = 0; i < tables.length; i++)
{
checkedLocationsArray[i] = tables[i][pos];
}
for(i=0;i<checkedLocationsArray.length;i++)
{
urlnow = checkedLocationsArray[i];
if(urlnow == url)
{
return true;
}
if(urlnow.indexOf('*') != -1)
{
while(urlnow.indexOf("*") != -1)
urlnow = urlnow.replace("*", "\\S+")
}
var regex = new RegExp(urlnow);
var Erg = regex.exec(url);
if(Erg != null && Erg == url)
return true;
}
}
return false;
}
}
}
Thanks for your help thought!

Related

Error in validating my password with Javascript

I am trying to check my user inputted password with a series of if statements and boolean variables within a function. It seems like my if statements are not modifying my boolean variables. Could someone tell me why?
I was trying to use (/[a-zA-z]/).test(pValue.charAt(0))) as a boolean to see if the first character entry was a lower or upper case letter, but that didn't work either.
document.querySelector("#enter").addEventListener("click", validate);
function validate(e) {
var count = false;
var firstChar = false;
var hasNum = false;
var special = false;
var pValue = document.querySelector("#passwrd").value;
var pLength = pValue.length;
console.log(pValue);
console.log(pLength);
if(pLength > 4 && pLength <= 8) {
count = true;
}
if(pValue.search(e.charCode === [65 - 90]) === 0) {
firstChar = true;
}
console.log(firstChar);
for(var j = 0; j < pLength; j++) {
if(pValue.charAt(j) == "$" || pValue.charAt(j) == "%" || pValue.charAt(j) == "#") {
special = true;
}
}
for(var i = 0; i < pLength; i++) {
if(!isNaN(pValue.charAt(i))) {
hasNum = true;
}
}
if(count && firstChar && hasNum && special) {
document.querySelector("#show_word").textContent = pValue;
}
}

SAPUI5 Filter OData model based on fields using formatter

I have a List that contains ObjectListItems with content provided by an OData service. One of this contents is the title and the property has the value as follows:
title="{ path: 'title', formatter: 'app.schedule.util.Formatter.titleText'}"
As you can see there is a formatter in this title. The OData will bring a value like "available" or "disabled" and the formatter will transform it on the text for the specific language of the user.
I'm implementing a search capability on this List and it works fine, the problem is that it searchs only on the "available" and "disabled" values, and not in the formatted texts as it would be expected as this are not the values recognized by the user.
The filter code is:
handleSearch : function (evt) {
// create model filter
var filters = [];
var query = evt.getParameter("query");
if (query && query.length > 0) {
filters.push(new sap.ui.model.Filter("booked", sap.ui.model.FilterOperator.Contains, query));
filters.push(new sap.ui.model.Filter("weekday", sap.ui.model.FilterOperator.Contains, query));
filters.push(new sap.ui.model.Filter("title", sap.ui.model.FilterOperator.Contains, query));
filters = new sap.ui.model.Filter(filters, false);
}
// update list binding
var list = this.getView().byId("list");
var binding = list.getBinding("items");
binding.filter(filters);
},
Any idea on how to consider the formatter on the filter and not only the raw data?
Solution Considering you are doing only client side search:
Assumption: if you have grouping in the list..
handleSearch : function (evt) {
sFilterPattern = evt.getParameter("query");
sFilterPattern = sFilterPattern.toLowerCase();
var aListItems = this.getView().byId("list").getItems();
var bVisibility;
var oGroupItem = null;
var iCountInGroup = 0;
for (var i = 0; i < aListItems.length; i++) {
if (aListItems[i] instanceof sap.m.GroupHeaderListItem) {
if (oGroupItem) {
if (iCountInGroup == 0) {
oGroupItem.setVisible(false);
} else {
oGroupItem.setVisible(true);
oGroupItem.setCount(iCountInGroup);
}
}
oGroupItem = aListItems[i];
iCountInGroup = 0;
} else {
bVisibility = this.applySearchPatternToListItem(aListItems[i], sFilterPattern);
aListItems[i].setVisible(bVisibility);
if (bVisibility) {
iCountInGroup++;
}
}
}
if (oGroupItem) {
if (iCountInGroup == 0) {
oGroupItem.setVisible(false);
} else {
oGroupItem.setVisible(true);
oGroupItem.setCount(iCountInGroup);
}
}
}
applySearchPatternToListItem:function(oItem, sFilterPattern) {
if (sFilterPattern == "") {
return true;
}
//uncomment to search in oModel data
/*var oIteshellata = oItem.getBindingContext(this.sModelName).getProperty();
for (var sKey in oIteshellata) {
var sValue = oIteshellata[sKey];
// if (sValue instanceof Date) {
// //just for the filter take each number as string
// sValue = sValue.getDate() + "." +
// sValue.getMonth() + "." + sValue.getFullYear();
// }
if (typeof sValue == "string") {
if (sValue.toLowerCase().indexOf(sFilterPattern) != -1) {
return true;
}
}
}*/
// if nothing found in unformatted data, check UI elements
if ((oItem.getIntro() && oItem.getIntro().toLowerCase().indexOf(sFilterPattern) != -1)
|| (oItem.getTitle() && oItem.getTitle().toLowerCase().indexOf(sFilterPattern) != -1)
|| (oItem.getNumber() && oItem.getNumber().toLowerCase().indexOf(sFilterPattern) != -1)
|| (oItem.getNumberUnit() && oItem.getNumberUnit().toLowerCase().indexOf(sFilterPattern) != -1)
|| (oItem.getFirstStatus() && oItem.getFirstStatus().getText().toLowerCase().indexOf(sFilterPattern) != -1)
|| (oItem.getSecondStatus() && oItem.getSecondStatus().getText().toLowerCase().indexOf(sFilterPattern) != -1)) {
return true;
}
// last source is attribute array
var aAttributes = oItem.getAttributes();
for (var j = 0; j < aAttributes.length; j++) {
if (aAttributes[j].getText().toLowerCase().indexOf(sFilterPattern) != -1) {
return true;
}
}
return false;
}

Check and alert for the null value

I need to check for the null values and alert them if there are any before getting saved. I have used this code but I am not able to alert the null values instead it is getting saved . .
function fn_publish() {
var SessionNames = getParameterByName('SessionName');
var MenuType = getParameterByName('MenuType');
var Date = getParameterByName('ForDate');
var publish = "Y";
Dates = Date.split("-");
Date = Dates[1] + "/" + Dates[2] + "/" + Dates[0];
var rows = [];
cols = document.getElementById('product_table').rows[1].cells.length - 1;
table = document.getElementById('product_table');
for (var i = 1; i <= cols; i++) {
for (var j = 0, row; row = table.rows[j]; j++) {
if (j == 0) {
cust = row.cells[i].innerText;
alert(cust);
} else if (j == 1) {
catlg = row.cells[i].innerText;
alert(catlg);
} else {
if (typeof (row.cells[i]) != "undefined") {
if (row.cells[i].innerText != "") {
//alert(SessionNames+"::"+MenuType+"::"+Date+"::"+catlg+"::"+row.cells[0].innerText+"::"+row.cells[i].innerText+"::"+cust+"::"+publish);
fn_insert(SessionNames, MenuType, Date, catlg, row.cells[0].innerText, row.cells[i].innerText, cust, publish);
} else {
jAlert("Please select a product", "ok");
return false;
}
}
}
}
}
jAlert("Menu Published", "ok");
}
if (row.cells[i].innerText != "") {
May be the cells are containing empty space in that. Better trim ad then compare.
if (row.cells[i].innerText.trim() !== "") {
Also instead of innerText use textContent which is common in most modern browsers.
if (row.cells[i].textContent.trim() !== "") {

Remove Required Field from QuickCreate in Sugarcrm

I wrote a function to remove accounts name relate field from Contacts QuickCreate but my function works in Firefox perfectly but in chrome its not working... Here is my function
function manageRequired(reqArr, disabledVal)
{
var requiredLabel = '<span class="required">*</span>'; // for firefox
var search_requiredLabel = '<span class="required"'; // searching string for firefox
var form = "";
for(var i = 0; i < document.forms.length; i++)
{
if(document.forms[i].id=='EditView')
{
form = 'EditView';
break;
}
if(document.forms[i].id=='form_SubpanelQuickCreate_Contacts')
{
form = 'form_SubpanelQuickCreate_Contacts';
break;
}
if(document.forms[i].id=='form_QuickCreate_Contacts')
{
form = 'form_QuickCreate_Contacts';
break;
}
if(document.forms[i].id=='form_QuickCreate_Accounts')
{
form = 'form_QuickCreate_Accounts';
break;
}
}
for(var j = 0; j < reqArr.length; j++)
{
var flag = true;
if (validate[form] != 'undefined')
{
for(var i = 0; i < validate[form].length; i++)
{
if(validate[form][i][0] == reqArr[j].id && validate[form][i][2])
{
if(disabledVal)
{
flag = false;
break;
}
else
{
validate[form][i][2] = false;
}
}
}
}
var labelNode = document.getElementById(reqArr[j].id + '_label');
if(flag & disabledVal)
{
// we require the field now
addToValidate(form, reqArr[j].id, reqArr[j].type, true,reqArr[j].label );
}
if(disabledVal)
{
if(labelNode != null && labelNode.innerHTML.indexOf(search_requiredLabel) == -1) // for IE replace search string
{
search_requiredLabel = '<SPAN class=required>';
}
if (labelNode != null && labelNode.innerHTML.indexOf(search_requiredLabel) == -1)
{
labelNode.innerHTML = labelNode.innerHTML.replace(requiredLabel, '');
labelNode.innerHTML = labelNode.innerHTML + requiredLabel;
}
}
else
{
if(labelNode != null)
{
if(labelNode != null && labelNode.innerHTML.indexOf("<SPAN class=required>*</SPAN>") == -1 && labelNode.innerHTML.indexOf('<span class="required">*</span>') == -1 )// for that field which is unrequired
{
}
else if(labelNode != null && labelNode.innerHTML.indexOf(requiredLabel) == -1) // for IE replace span string
{
requiredLabel = "<SPAN class=required>*</SPAN>";
}
labelNode.innerHTML = labelNode.innerHTML.replace(requiredLabel, '');
}
}
}
}
Can anyone please help me out to solve this issue...
To remove a required field from QuickCreate in Sugarcrm you can use this fuction:
removeFromValidate('EditView','eventlist_c');
or remove remove the validtion applied to the field:
$('#eventlist_c_label').html('{$mod_strings['LBL_EVENTLIST']}: ');

Javascript Phone number validation Paratheses sign

I did some searching and there where others asking this question and answers to it but none that seemed to fit what I was trying to do. Basically I'm working on a validation of the phone entry that accepts (123)4567890 as an entry. I've already implemented one that accepts a simple number string such as 1234567890 and one with dashes 123-456-7890. I know I'm making a simple mistake somewehre but I can't figure out what I'm doing wrong.
Here's the phone number with dashes form that is working:
//Validates phone number with dashes.
function isTwelveAndDashes(phone) {
if (phone.length != 12) return false;
var pass = true;
for (var i = 0; i < phone.length; i++) {
var c = phone.charAt(i);
if (i == 3 || i == 7) {
if (c != '-') {
pass = false;
}
}
else {
if (!isDigit(c)) {
pass = false;
}
}
}
return pass;
}​
and this is the one I can't manage to work out.
function isTwelveAndPara(phone) {
if (phone.length != 12) return false;
var pass = true;
for (var i = 0; i < phone.length; i++) {
var c = phone.charAt(i);
if (i == 0) {
if (c != '(') {
pass = false;
}
}
if (i == 4) {
if (c != ')') {
pass = false;
}
}
else {
if (!isDigit(c)) {
pass = false;
}
}
}
return pass;
}​
You can do it very easily with regex:
return !!phone.match(/\(\d{3}\)\d{7}/g)
Live DEMO
Update:
The code you had didn't work because you forgot the else if:
else if (i == 4) { // Added the "else" on the left.
Checking phone number with RegEx is certainly the way to go. Here is the validation
function that ignores spaces, parentheses and dashes:
check_phone(num) {
return num.replace(/[\s\-\(\)]/g,'').match(/^\+?\d{6,10}$/) != null}
You can vary the number of digits to accept with the range in the second regular expression {6,10}. Leading + is allowed.
Something like that (a RegExp rule) can make sure it matches either rule.
var numbers = ['(1234567890','(123)4567890','123-456-7890','1234567890','12345678901'];
var rule = /^(\(\d{3}\)\d{7}|\d{3}-\d{3}-\d{4}|\d{10})$/;
for (var i = 0; i < numbers.length; i++) {
var passed = rule.test(numbers[i].replace(/\s/g,''));
console.log(numbers[i] + '\t-->\t' + (passed ? 'passed' : 'failed'));
}
EDIT:
function isDigit(num) {
return !isNaN(parseInt(num))
}
function isTwelveAndPara(phone) {
if (phone.length != 12) return false;
for (var i = 0; i < phone.length; i++) {
var c = phone.charAt(i);
if (i == 0) {
if (c != '(') return false;
} else if (i == 4) {
if (c != ')') return false;
} else if (!isDigit(c)) return false;
}
return true;
}
// or...
function isTwelveAndPara(phone) {
if (phone.length != 12 || phone.charAt(0) != '(' || phone.charAt(4) != ')') return false;
for (var i = 1; i < phone.length, i != 4; i++) {
if (!isDigit(phone.charAt(i))) return false;
}
return true;
}

Categories

Resources