hello i am using javascript to validate field
i am checking special characters.. the code i am implementing validates all the special characters except _ underscore..
<script type="text/javascript" language="javascript">
function validateForm()
{
var iChars = "!##$%^&*()+=-[]\\\';,./{}|\":<>?_";
for (var i = 0; i < document.reg_form.txtusername.value.length; i++)
{
if (iChars.indexOf(document.reg_form.txtusername.value.charAt(i)) != -1)
{
alert ("Special Characters are not allowed.");
return false;
}
}
return true;
}
</script>
for this filed
<input name="txtusername" type="text" id="txtusername" maxlength="10" style="background-color:#CCC" />
but its not validating the underscore
Would it not make sense to just shove it into your iChars variable, which is quite obviously your "blacklist"?
var iChars = "!##$%^&*()+=-[]\\\';,./{}|\":<>?_";
var iChars = "!##$%^&*()+=-[]\\\';,./{}|\":<>?_";
for (var i = 0; i < document.reg_form.firstname.value.length; i++)
{
if (iChars.indexOf(document.reg_form.firstname.value.charAt(i)) != -1)
{
alert ("Special Characters are not allowed");
return false;
}
}
characters in strings can be addressed as if the string were an array (which, if you think about it, it is). Since you're looping through the string char-per-char, again, as you would with an array, why not be consistent in your logic?
if (iChars.indexOf(document.reg_form.firstname.value[i]) !== -1)
{
alert('Foobar');
return false;
}
That should work... Also: there's no real need to escape the single quote, since the iChar string is delimited by double quotes... if all else fails, you might want to try omitting that backslash, too. Though I don't think that's what's causing the problem
It is working: here
Related
I have an HTML page on the admin site for managing user on a HTML/Javascript/PHP system that runs on browsers. I have close to 20 inputboxes because on one page i have combined several forms of new_user, forgot_password, Change_password and Edit_user_details.
This code is what i used to check the username's empty field, this means i have to write 20 of this lines;
My concern is--> How do i write a short, summarized but effective javascript code to check on empty fields. (I will also need to validate fields like digits, numbers, length, emails etc)
function RequiredFields(){
var username=document.forms["login"]["username"].value;
if (username==""||username==null){
alert("empty username")
document.login.username.focus();
if(document.all||document.getElementById){
document.login.username.style.background="pink";
}
return false;
}
}
You can use jQuery to check for empty fields, have a look at this code:
function Validate() {
$('form input[type="text"]').each(function(){
if (this.value=="")
alert('Value Required');
});
}
To validate things like emails, numbers etc, you would need to write a separate function for those particular text boxes.
See here: http://jsfiddle.net/TgCbB/1/
HTML
<input type="text" id="username" class="required" data-default="User Name"/>
<input type="text" id="email" class="required email" data-default="Email"/>
<input type="text" id="digits" class="required digits" data-default="Integer"/>
The important thing to note here is the class attribute, which indicates how it should be validated. (You could do this with a data- attribute, which would be better, but I used class for backwards compatibility).
You can now, with plain javascript, validate like so:
function validate(e){
var invalid = [];
var required = document.getElementsByClassName("required");
for (var i = 0; i < required.length; i++){
var req = required[i];
var val = req.value || "";
var def = req.hasAttribute("data-default") ? req.getAttribute("data-default") : "";
if (val == "" || val == def)
invalid.push(req);
req.className = req.className.replace(" invalid","");
}
var digits = document.getElementsByClassName("digits");
for (var i = 0; i < digits.length; i++){
var dig = digits[i];
var val = Number(dig.value || "");
var rem = val - Math.floor(val);
if (rem != 0)
invalid.push(dig);
dig.className = dig.className.replace(" invalid","");
}
var emails = document.getElementsByClassName("email"),
reg = /^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
for (var i = 0; i < emails.length; i++){
var em = emails[i];
var val = em.value || "";
if (!reg.test(val))
invalid.push(em);
em.className = em.className.replace(" invalid", "");
}
for (var i = 0; i < invalid.length; i++){
var inp = invalid[i];
var cls = inp.className.replace(" invalid", "");
inp.className = cls + " invalid";
}
}
Note that the could be made less verbose, but I opted for readability. The concept is, get each item with the class name we're validating against, iterate over them, and then mark it as invalid if it doesn't pass validation.
I found a nice little script on snippr(http://snipplr.com/view.php?codeview&id=799) that gives me the GET variables in an associative array.
// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
var get = getUrlVars();
I am trying to check to see if a certain GET variable is set and if the value is 'search'. For some reason my code is not catching the If statement and alerting even if the condition is not met.
if((get['search_housing']) = 'search') {
alert('this works');
}
I'm not sure why it's not respecting my If statement. Is there something wrong with my code?
The = operator sets the value.
You're looking for ==, which compares values:
if((get['search_housing']) == 'search') {
alert('this works');
}
if((get['search_housing']) == 'search') {
DOUBLE equals!
Maybe it needs to be this:
if((get['search_housing']) == 'search') {
alert('this works');
}
See, the = would mean you are trying to assign 'search' to the get[].
if(get('search_housing')==='search'){
alert('test');
}
Try gup instead. That code you found doesn't look very robust. You probably want to unescape the returned value because you are comparing the results.
if (gup('search_housing') == 'search') { ... }
function gup( 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 results[1];
}
After an earlier question relating to this error.
Error: unable to get value of the property ‘split’: object is null or undefined
An answer was offered to add the following code:
/* Cross-Browser Split 1.0.1
(c) Steven Levithan <stevenlevithan.com>; MIT License
An ECMA-compliant, uniform cross-browser split method */
var cbSplit;
// avoid running twice, which would break `cbSplit._nativeSplit`'s reference to the native `split`
if (!cbSplit) {
cbSplit = function (str, separator, limit) {
// if `separator` is not a regex, use the native `split`
if (Object.prototype.toString.call(separator) !== "[object RegExp]") {
return cbSplit._nativeSplit.call(str, separator, limit);
}
var output = [],
lastLastIndex = 0,
flags = (separator.ignoreCase ? "i" : "") +
(separator.multiline ? "m" : "") +
(separator.sticky ? "y" : ""),
separator = RegExp(separator.source, flags + "g"), // make `global` and avoid `lastIndex` issues by working with a copy
separator2, match, lastIndex, lastLength;
str = str + ""; // type conversion
if (!cbSplit._compliantExecNpcg) {
separator2 = RegExp("^" + separator.source + "$(?!\\s)", flags); // doesn't need /g or /y, but they don't hurt
}
/* behavior for `limit`: if it's...
- `undefined`: no limit.
- `NaN` or zero: return an empty array.
- a positive number: use `Math.floor(limit)`.
- a negative number: no limit.
- other: type-convert, then use the above rules. */
if (limit === undefined || +limit < 0) {
limit = Infinity;
} else {
limit = Math.floor(+limit);
if (!limit) {
return [];
}
}
while (match = separator.exec(str)) {
lastIndex = match.index + match[0].length; // `separator.lastIndex` is not reliable cross-browser
if (lastIndex > lastLastIndex) {
output.push(str.slice(lastLastIndex, match.index));
// fix browsers whose `exec` methods don't consistently return `undefined` for nonparticipating capturing groups
if (!cbSplit._compliantExecNpcg && match.length > 1) {
match[0].replace(separator2, function () {
for (var i = 1; i < arguments.length - 2; i++) {
if (arguments[i] === undefined) {
match[i] = undefined;
}
}
});
}
if (match.length > 1 && match.index < str.length) {
Array.prototype.push.apply(output, match.slice(1));
}
lastLength = match[0].length;
lastLastIndex = lastIndex;
if (output.length >= limit) {
break;
}
}
if (separator.lastIndex === match.index) {
separator.lastIndex++; // avoid an infinite loop
}
}
if (lastLastIndex === str.length) {
if (lastLength || !separator.test("")) {
output.push("");
}
} else {
output.push(str.slice(lastLastIndex));
}
return output.length > limit ? output.slice(0, limit) : output;
};
cbSplit._compliantExecNpcg = /()??/.exec("")[1] === undefined; // NPCG: nonparticipating capturing group
cbSplit._nativeSplit = String.prototype.split;
} // end `if (!cbSplit)`
// for convenience...
String.prototype.split = function (separator, limit) {
return cbSplit(this, separator, limit);
};
After trialling the code above and deleting caches it was found to do nothing...can anyone help at all, kind regards in advance.
Thanks EdoDodo for the above code but can you offer any further help as I am almost tearing my hair out and it did not work in the end, one point to note, the linked in button on the home page (if commented out) makes that site work for the home page and the error goes away but I really want the linked in buttons for each post excerpt on the home page.
site is:
www.mobileinquirer.com
Firefox shows me a script error on line 913 in this part of your script:
<script type="text/javascript">
// <![CDATA[
var disqus_shortname = 'mobileinquirer';
var disqus_domain = 'disqus.com';
(function () {
var nodes = document.getElementsByTagName('span');
for (var i = 0, url; i < nodes.length; i++) {
if (nodes[i].className.indexOf('dsq-postid') != -1) {
nodes[i].parentNode.setAttribute('data-disqus-identifier', nodes[i].getAttribute('rel'));
url = nodes[i].parentNode.href.split('#', 1);
if (url.length == 1) url = url[0];
else url = url[1]
nodes[i].parentNode.href = url + '#disqus_thread';
}
}
var s = document.createElement('script'); s.async = true;
s.type = 'text/javascript';
s.src = 'http://' + disqus_domain + '/forums/' + disqus_shortname + '/count.js';
(document.getElementsByTagName('HEAD')[0] || document.getElementsByTagName('BODY')[0]).appendChild(s);
}());
//]]>
</script>
The specific error is on this line:
url = nodes[i].parentNode.href.split('#', 1);
and it's because parentNode does not have an href. This error has nothing to do with the split function. The code is trying to obtain the value of the href attribute on the parentNode, but there is no href attribute so that resolves to undefined so the call to split fails. It has nothing to do with the split function. The issue is that your markup is apparently wrong and what I think is disqus code is expecting an tag around a tag, but it isn't finding that.
If you look at line 664-665 in the mobilinquirer.com HTML source, you will find this sequence at that line and then several times following:
<p><span
class="dsq-postid">8 Comments</span></p>
This code causes the error. The <span class="dsq-postid"> tag must have an <a href="xxx"> tag as it's parent or you will get this error. I see this same problem several problems in your HTML.
This problem has NOTHING to do with the split function. To make this error go away, you need to fix your HTML so that it is what the disqus code is expecting or remove the offending disqus code (which you don't seem to need) or both.
I am trying to get list of image path from my db and with help of Jquery and Json triying to add to my site. But I dont know why after encoding my string usingjson_encode` in php it changes it path and shows me like
[{"0":"user\/photogallery\/images\/members\/2\/2_1.jpg","src":"user\/photogallery\/images\/members\/2\/2_1.jpg"},{"0":"user\/photogallery\/images\/members\/2\/2_2.jpg","src":"user\/photogallery\/images\/members\/2\/2_2.jpg"}]
I need only user/photogallery/images/members/2/2_2.jpg part to create new <img src ="user/photogallery/images/members/2/2_2.jpg " /> component.
Here my php code and script
$member_id = $GET['member_id'];
$files = find_all_photos($member_id);
$encoded = json_encode($files);
echo $encoded;
unset($encoded);
function find_all_photos($id)
{
db_connect();
$query = sprintf("SELECT src FROM photo_album_list WHERE user_id = '%s'",
mysql_real_escape_string($id));
$result = mysql_query($query);
$result = db_result_to_array($result);
return $result;
}
function db_result_to_array($result)
{
$res_array = array();
for ($count=0; $row = mysql_fetch_array($result); $count++)
{
$res_array[$count] = $row;
}
return $res_array;
}
And script
$.get('photostack.php', {member_id:2} , function(data) {
console.log(data);
var items_count = data.length;
for(var i = 0; i < items_count; ++i){
var item_source = data[i];
var cnt = 0;
$('<img />').load(function(){
var $image = $(this);
++cnt;
resizeCenterImage($image);
$ps_container.append($image);
var r = Math.floor(Math.random()*41)-20;
if(cnt < items_count){
$image.css({
'-moz-transform' :'rotate('+r+'deg)',
'-webkit-transform' :'rotate('+r+'deg)',
'transform' :'rotate('+r+'deg)'
});
}
if(cnt == items_count){
$loading.remove();
$ps_container.show();
$ps_close.show();
$ps_overlay.show();
}
}).attr('src',item_source);
}
},'json');
It sounds like you're bothered that backslashes are being added prior to the slashes in the path. Completely agree that that's very odd (there's no need whatsoever to "escape" a slash in JSON strings), but in most notations it's harmless to escape a character that doesn't require escaping if that character doesn't have a special escaped meaning. (That is, it's harmless to escape / even though it doesn't need it, but obviously not harmless to escape n even though it doesn't mean it, since \n means something).
To my eyes, the JSON page is silent on what to do with invalid escapes, but Crockford's own parser allows them (disregards the unnecessary backslash), so... (Crockford being the inventor of JSON.)
It's possible that the escaped backslashes are stored in the DB that way, so your JSON string is just pulling them verbatim. If you want to remove them you'll need to process the string returned from the DB before you return or json_encode() them.
Ok, I've been banging my head up against the wall on this and I have no clue why it isn't creating the element. Maybe something very small that I overlooked here. Basically, there is this Javascript code that is in a PHP document being outputted, like somewhere in the middle of when the page gets loaded, NOW, unfortunately it can't go into the header. Though I'm not sure that that is the problem anyways, but perhaps it is... hmmmmm.
// Setting the variables needed to be set.
echo '
<script type="text/javascript" src="' . $settings['default_theme_url'] . '/scripts/shoutbox.js"></script>';
echo '
<script type="text/javascript">
var refreshRate = ', $params['refresh_rate'], ';
createEventListener(window);
window.addEventListener("load", loadShouts, false);
function loadShouts()
{
var alldivs = document.getElementsByTagName(\'div\');
var shoutCount = 0;
var divName = "undefined";
for (var i = 0; i<alldivs.length; i++)
{
var is_counted = 0;
divName = alldivs[i].getAttribute(\'name\');
if (divName.indexOf(\'dp_Reserved_Shoutbox\') < 0 && divName.indexOf(\'dp_Reserved_Counted\') < 0)
continue;
else if(divName == "undefined")
continue;
else
{
if (divName.indexOf(\'dp_Reserved_Counted\') == 0)
{
is_counted = 0;
shoutCount++;
continue;
}
else
{
shoutCount++;
is_counted = 1;
}
}
// Empty out the name attr.
alldivs[i].name = \'dp_Reserved_Counted\';
var shoutId = \'shoutbox_area\' + shoutCount;
// Build the div to be inserted.
var shoutHolder = document.createElement(\'div\');
shoutHolder.setAttribute(\'id\', [shoutId]);
shoutHolder.setAttribute(\'class\', \'dp_control_flow\');
shoutHolder.style.cssText = \'padding-right: 6px;\';
alldivs[i].parentNode.insertBefore(shoutHolder, alldivs[i]);
if (is_counted == 1)
{
startShouts(refreshRate, shoutId);
break;
}
}
}
</script>';
Also, I'm sure the other functions that I'm linking to within these functions work just fine. The problem here is that within this function, the div never gets created at all and I can't understand why? Furthermore Firefox, FireBug is telling me that the variable divName is undefined, even though I have attempted to take care of this within the function, though not sure why.
Anyways, I need the created div element to be inserted just before the following HTML:
echo '
<div name="dp_Reserved_Shoutbox" style="padding-bottom: 9px;"></div>';
I'm using name here instead of id because I don't want duplicate id values which is why I'm changing the name value and incrementing, since this function may be called more than 1 time. For example if there are 3 shoutboxes on the same page (Don't ask why...lol), I need to skip the other names that I already changed to "dp_Reserved_Counted", which I believe I am doing correctly. In any case, if I could I would place this into the header and have it called just once, but this isn't possible as these are loaded and no way of telling which one's they are, so it's directly hard-coded into the actual output on the page of where the shoutbox is within the HTML. Basically, not sure if that is the problem or not, but there must be some sort of work-around, unless the problem is within my code above... arrg
Please help me. Really what I need is a second set of eyes on this.
Thanks :)
When you're testing divName, switch the order of your conditions from this
divName = alldivs[i].getAttribute(\'name\');
if (divName.indexOf(\'dp_Reserved_Shoutbox\') < 0 && divName.indexOf(\'dp_Reserved_Counted\') < 0)
continue;
else if(divName == "undefined")
continue;
to this:
var divName = alldivs[i].getAttribute(\'name\');
if (!divName) // this is sufficient, by the way
continue;
else if (divName.indexOf(\'dp_Reserved_Shoutbox\') < 0 && divName.indexOf(\'dp_Reserved_Counted\') < 0)
continue;
The problem is that when the script finds a div without a name, it tries to call the indexOf property of a non-existent value and therefore throws an error.
There were a number of issues in the loadShouts method. First being the comparison of a string "undefined" instead of a straight boolean check, which will match. I also removed a bunch of un-needed logic. Beyond this, the id attribute being assigned to the new shoutHolder was being passed in as an array, instead of a direct property assignment.. See if the following works better.
function loadShouts()
{
var alldivs = document.getElementsByTagName("div");
var shoutCount = 0;
var divName = "undefined";
for (var i = 0; i<alldivs.length; i++)
{
divName = alldivs[i].getAttribute("name");
if (!divName)
continue;
if (divName.indexOf("dp_Reserved_Shoutbox") < 0 && divName.indexOf("dp_Reserved_Counted") < 0)
continue;
shoutCount++;
if (divName.indexOf("dp_Reserved_Counted") == 0)
continue;
// Empty out the name attr.
alldivs[i].setAttribute("name", "dp_Reserved_Counted");
var shoutId = "shoutbox_area" + shoutCount;
// Build the div to be inserted.
var shoutHolder = document.createElement("div");
shoutHolder.setAttribute("id", shoutId);
shoutHolder.setAttribute("class", "dp_control_flow");
shoutHolder.style.cssText = "padding-right: 6px;";
alldivs[i].parentNode.insertBefore(shoutHolder, alldivs[i]);
startShouts(refreshRate, shoutId);
break;
}
}
Ok, just wanted to let you know how it went. And I thank both you greatly Tracker1 and Casey Hope. Especially Tracker for the excellent rewrite of the function. You all ROCK. Here's the final function that I'm using bytheway, just a tiny bit of editing to Tracker1's Answer, which is why you got my vote hands down!
echo '
<script type="text/javascript">
var refreshRate = ' . $params['refresh_rate'] . ';
createEventListener(window);
window.addEventListener("load", loadShouts, false);
function loadShouts()
{
var alldivs = document.getElementsByTagName("div");
var shoutCount = 0;
var divName = "undefined";
for (var i = 0; i<alldivs.length; i++)
{
divName = alldivs[i].getAttribute("name");
if (!divName)
continue;
if (divName.indexOf("dp_Reserved_Shoutbox") < 0 && divName.indexOf("dp_Reserved_Counted") < 0)
continue;
shoutCount++;
if (divName.indexOf("dp_Reserved_Counted") == 0)
continue;
// Empty out the name attr.
alldivs[i].setAttribute("name", "dp_Reserved_Counted");
var shoutId = "shoutbox_area" + shoutCount;
// Build the div to be inserted.
var shoutHolder = document.createElement("div");
shoutHolder.setAttribute("id", shoutId);
shoutHolder.setAttribute("class", "dp_control_flow");
shoutHolder.style.cssText = "padding-right: 6px;";
alldivs[i].parentNode.insertBefore(shoutHolder, alldivs[i]);
startShouts(refreshRate, shoutId);
break;
}
}
</script>';
Thanks Again, you are the BEST!