I need to do a URL validation for a CS form. I already have a script there that that checks for http and adds it if not there. However, if I add another function to do just validation, no matter where I put it, it returns URL invalid.
This is what I am running
<script type="text/javascript">
$(function(){
$('.url').blur(function(e) {
if ($(this).val().match(/^http/) || $(this).val().match(/^https/)) /*define the http & https strings */ {
$.noop() /*if strings exist, do nothing */
}
else {
// get value from field
var cur_val = $(this).val();
// do with cur_val
$(this).val('http://' + cur_val);
}
});
});
</script>
This is the second function I used for validation:
<script type="text/javascript">
function validate() {
var url = document.getElementById("url").value;
var pattern = /(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/;
if (pattern.test(url)) {
alert("Url is valid");
return true;
}
alert("Url is not valid!");
return false;
}
</script>
What am I doing wrong? I've tried to merge the 2 functions but my js skills choose that exact moment to fail.
Thank you!
I don't know, if this is what you are exactly looking for,
var pattern = /(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/;
pattern.test("http://google.com"); // True
pattern.test("google.com"); // False
The if condition you are using is useless, since you return the result of the pattern match anyway.
So the updated Validate function should simply return the pattern results & should look like:
function validate() {
var url = document.getElementById("url").value;
var pattern = /(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/;
return pattern.test(url);
}
Assuming that there is a DOM element with id url.
Just from an immediate look, it looks like your "add http" function is looking for tags with class="url", while the validate function is looking for tags with id="url". If you have nothing with that id, then I suppose it would always return invalid.
Related
I have a Client Script that performs a GlideRecord query to check if a record already exists with the same name.
If a matching record is found, we need to STOP the form from being submitted.
We have this working fine on the CMS portal.
However, the new Service Portal does not support synchronous GlideRecord query.
So I can't use gr.query() I need to use a callback such as gr.query(callback).
The issue is that since the callback is asynchronous, it does not actually stop the form from being submitted!
g_form.submitted = false; DOES NOT work. That's because the script proceeds along to submit the form before the callback has a chance to retrieve the value.
How can we stop the submission of a form based on the value returned by an asynchronous callback? We can't use GlideAjax for the same reason, getXMLWait() is no longer supported.
Here is the client script that I am trying to get working in the new Service Portal.
function onSubmit() {
var group_name = g_form.getValue('u_group_name');
g_form.hideAllFieldMsgs('error');
/*Check if group already exists*/
var rec = new GlideRecord('u_auth_group');
rec.addQuery('u_group_name', u_group_name);
rec.query(getAccountResponse);
}
function getAccountResponse(rec) {
while (rec.next()) {
g_form.showFieldMsg('u_group_name', " Group Name exists already, please select another group name",'error');
g_form.submitted = false; //DOES NOT STOP THE FORM FROM BEING SUBMITTED
return false;
}
}
Here is the existing script that works in the CMS portal.
function onSubmit() {
var group_name = g_form.getValue('u_group_name');
g_form.hideAllFieldMsgs('error');
/*Check if group already exists*/
var rec = new GlideRecord('u_auth_group');
rec.addQuery('u_group_name', u_group_name);
rec.query(getAccountResponse);
while (rec.next()) {
g_form.showFieldMsg('u_group_name', " Group Name exists already, please select another group name",'error');
g_form.submitted = false; //Stops the form from being submitted if a result is returned
return false;
}
}
We're on Helsinki Patch 5 so we're going through similar growing pains. We've had luck using the following structure. There are still Glide System resources available Server Side, including Glide Record.
You might try wrapping your Submit action inside of a custom event handler.
Try:
Client side:
c.createGroup = function(groupName){
return c.server.get({
grpname : groupName
}.then(function(response){
if (response.data.result == true){
//don't submit
}
else{
//submit
}
}
Server Side
data.result = false
data.grpname = input.grpname
function checkGroupExists(data.grpname){
/*Check if group already exists*/
var rec = new GlideRecord('u_auth_group');
rec.addQuery('u_group_name', data.grpname);
rec.limit(1); //you only need to find one match
rec.query()
while (rec.next()){
data.result = true
}
}
Then you can bind this event handler to some action in the UI.
I was able to solve this by using an asyc callback with the glide record query.
function onSubmit() {
//If ServicePortal
if (!window) {
if (g_scratchpad.isFormValid) {
return true;
}
g_form.hideAllFieldMsgs("error");
var actionName = g_form.getActionName();
//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);
//Check if google group already exists
var gg = new GlideRecord("u_system_group");
gg.addQuery("u_group_name", group_name);
//Callback function to control stop submit asynchronously
gg.query(function() {
while (gg.next()) {
g_form.showFieldMsg("u_group_name","Group Name " + gg.u_group_name + " already exists! Please enter a different group name.", "error", true);
return false;
}
g_scratchpad.isFormValid = true;
g_form.submit(actionName);
});
return false;
}
}
I tried to make Ajax form and tried to make email verification there. I found this solution
http://jsfiddle.net/EFfCa/
but can't turn it on in my script:
<script>
$('#joinForm').ajaxForm(function() {
var testEmail = /^[A-Z0-9._%+-]+#([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
var name = $("input[name=name]")
var email = $("input[name=email]")
if(name.val()==''||email.val()=='') {
$(".notify").show();
$(".notify p").text('empty');
} else if(testEmail.test(email.value)) {
$(".notify").show();
$(".notify p").text('email is wrong');
} else {
$(".notify").show();
$(".notify p").text('good');
}
});
</script>
The form always passed verification even email is wrong. Verification for empty fields works good...
The following line else if(testEmail.test(email.value)) will return true if the email is correct.
In your logic that's where the email is wrong could that be the problem?
This is because your passing email.value. jquery objects don't have a parameter called value, so this will resolve as undefined.
.test() returns true if it is passed undefined, so your test will always pass.
use .val() instead.
$('input').blur(function() {
var testEmail =/^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
if (testEmail.test(this.value)) alert('passed');
else alert('failed');
});
How can I remove "http://" from beginning of a URL inside view in an AngularJS app?
I have URLs in database like:
http://example.com/
http://example.com
example.com
but I only need to show
example.com
inside the view.
This deals with HTTP and HTTPS or any other URL. It uses the built-in URL class, which will handle all of the things you haven't thought of correctly.
app.filter('domain', function () {
return function (input) {
try {
var url = new URL(input);
return url.hostname;
} catch (DOMException) {
// Malformed URL. Return original (or something else).
return input; }
};
});
URLs that are correct and you might not have thought of:
http://example.com
http://example.com:8000
http://me#example.com
file://example.com
https://example.com
http://example.com/some-path
http://example.com?some-query-url
You may not need them now, but using the correct library function means your app won't break unexpectedly in future when someone tries to use it for something else.
use this filter in view
app.filter('domain', function () {
return function (input) {
var output = "",
matches;
var urls = /\w+:\/\/([\w|\.]+)/;
matches = urls.exec( input );
if (matches !== null) output = matches[1];
return output;
};
});
I have a querystring which looks like this page3.html?redesigndata=value which it appears if its redirected from page1.html and page3.html?new=yes or no when redirected from page2.html. Here is the code I'm using to find out what the querystring is and do some functions on page3.html
var locurl = window.location.search;
if (locurl.substring(0, 13) === '?redesigndata') {
alert("redesign!");
} else if (locurl.substring(0, 4) === '?new') {
visit = locurl.substring(5);
alert("somthing!");
if (visit === 'yes') {
alert("first!");
} else if (visit === 'no') {
alert("again!");
}
}
but I don't get any alerts when I try this script and I cant find out what's wrong with it.
Try using this function
function getQueryString() {
var result = {}, queryString = location.search.substring(1),
re = /([^&=]+)=([^&]*)/g, m;
while (m = re.exec(queryString)) {
result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}
return result;
}
// ...
var myParam = getQueryString()["myParam"];
Check like this
if(getQueryString()["redesigndata"] != "")
There is nothing wrong with the code you posted. If the alerts never fire, it's because the conditions are never met. Once a query string is added to the URL that DOES match one of those you listed in your code, the alert does fire.
Also, beware you're (seemingly) creating global vars.
The script works on my box. Please put this script inside script tags
I have a javascript on my server, and i need to set a value / calling a function inside the javascript when calling a URL. Is there anyway of doing that ?
UPDATE:
<script type="application/x-javascript" src="test-test.js"></script>
Thats how it its loaded on the HTML site. And I want to call the function test(e,e) inside test-test.js, by putting in the URL in a browser with some values for e,e..
Unless you are using one of the few web servers that employs server-side JavaScript, your script is going to run in the browser after the page is loaded. If you want to include information from the URL in your script (and this assumes that you can use a query string without changing the server's behavior), you can use window.location.search to get everything from the question mark onwards.
This function will return either the entire query string (without the question mark) or a semicolon-delimited list of values matching the name value you feed it:
function getUrlQueryString(param) {
var outObj = {};
var qs = window.location.search;
if (qs != "") {
qs = decodeURIComponent(qs.replace(/\?/, ""));
var paramsArray = qs.split("&");
var length = paramsArray.length;
for (var i=0; i<length; ++i) {
var nameValArray = paramsArray[i].split("=");
nameValArray[0] = nameValArray[0].toLowerCase();
if (outObj[nameValArray[0]]) {
outObj[nameValArray[0]] = outObj[nameValArray[0]] + ";" + nameValArray[1];
}
else {
if (nameValArray.length > 1) {
outObj[nameValArray[0]] = nameValArray[1];
}
else {
outObj[nameValArray[0]] = true;
}
}
}
}
var retVal = param ? outObj[param.toLowerCase()] : qs;
return retVal ? retVal : ""
}
So if the URL was, say:
http://www.yoursite.com/somepage.html?name=John%20Doe&occupation=layabout
if you call getUrlQueryString() you would get back name=John Doe&occupation=layabout. If you call getUrlQueryString("name"), you would get back John Doe.
(And yes, I like banner-style indents. So sue me.)
You can use address plugin to be able to pass some condition in urls trough # symbol: http://my_site/my_page#your_condition
in the html you can write something like this:
<script>
$(function(){
// Init and change handlers
$.address.init().change(function(event) {
if (event.value == "your_condition")
run_my_finction();
});
)};
<script>
See this exaple for the futher help.
If you want to execute JavaScript from the browsers' address bar, you can use a self-invoking function:
javascript:(function () {
alert('Hello World');
/* Call the JavaScript functions you require */
})();