13 Replies - 3695 Views - Last Post: 10 June 2011 - 04:01 AM

#1 svpam123  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 47
  • Joined: 01-April 11

javascript function doesn't respond

Posted 08 June 2011 - 03:46 AM

hey again.
in my website I have a couple of forms that you can only see them if certain conditions are applied.
for example - if you're an admin and you search a user, you'll see a form which allows you to edit his information. if you're not you won't see it.
if you're already logged in you can't see the registration form, but if you aren't you can.
so I did it with ASP in this way - (this is the registration part)
if (Session["LoggedIn"] != null)
    {
        Response.Write("You're already registered!");
    }
else
{
Response.Write();
}


I've managed to put in the form inside the Response.Write(), and it also has the javascript part like this -
+ "<script type='text/javascript' src=ValidateData.js>"
+ "</script>"


this works perfectly fine.

now, I've done this twice. the example above is from the registration part which doesn't allow a logged in user to register again.

I'm having problems with the second one - not showing the edit form to a user who can't edit.
this is basically the code -

 if (Session["LoggedIn"] != null && ((Session["IsAdmin"] != null) || (Request.QueryString["SelfEdit"] == "Yes") || ((string)(Session["LoggedIn"]) == UserId)))
    {
        Response.Write(
            "<script type='text/javascript' src='ValidateData2.js'>"
            + "</script>"
            +"<form id='form1' name='form1' action='UpdateData.aspx' method='post' onsubmit='return validateForm(this)>"
            + "First name: "+ "<input id='Fname' name='Fname' type='text'>" 
            + "<br>"
            + "Last name: " + "<input id='Lname' name='Lname' type='text'>"
            + "<br>"
            + "Password: " + "<input id='Password' name='Password' type='password'>"
            + "<br>"
            + "Validate pass: " + "<input id='pass2' name='pass2' type='password'>"
            + "<br>"
            + "Email: " + "<input id='Email' name='Email' type='text'>"
            + "<br>"
            + "Age: " + "<input id='Age' name='Age' type='text'>"
            + "<br>"
            + "<input id='Submit1' type='submit' value='Edit!' />"
            + "</form>"
            );



this is the ValidateData2.js -
function validateForm(form1) {

          if (form1.Password.value > 0) {
              if (form1.pass2.value.length == 0) {
                  alert("Please validate password");
                  return false;
              }
              if (form1.Password.value != form1.pass2.value) {
                  alert("Please enter matching passwords!");
                  return false;
              }
              if (form1.Password.value.length < 6) {
                  alert("Passwords are too short!");
                  return false;

              }
          }

          if (form1.Email.value > 0) {
              if (form1.Email.value.indexOf('@') == -1) {
                  alert("Email must have '@'");
                  return false;
              }
              if (form1.Email.value.indexOf('.') == -1) {
                  alert("Email must have '.'");
                  return false;
              }
              if (form1.Email.value.length < 3) {
                  alert("Please enter a proper email address");
                  return false;
              }
          }

          if (form1.Age.value> 0) {
              if (isNaN(form1.Age) == true) {
                  alert("Age must be in numbers!");
                  return false;
              }
          }

   
          return true;
}



now this doesn't do anything... the submit button just ignores the JS file and just submits the form the way it is, unlike the other form which is written pretty much in the same way except for other JS fields/text boxes.

any ideas? did I miss anything?

I know the code is written really poorly but thats unfortunately what we've been taught in class and thats all I know.
help would be really really appreciated!
thanks!

*I'm not checking for nulls because if a field is empty it means the information won't be edited.

This post has been edited by svpam123: 08 June 2011 - 03:47 AM


Is This A Good Question/Topic? 0
  • +

Replies To: javascript function doesn't respond

#2 ahmad_511  Icon User is offline

  • MSX
  • member icon

Reputation: 131
  • View blog
  • Posts: 722
  • Joined: 28-April 07

Re: javascript function doesn't respond

Posted 09 June 2011 - 02:24 AM

Hi,
I think you forgot to close the onsubmit single qoute;
<form id='form1' name='form1' action='UpdateData.aspx' method='post' onsubmit='return validateForm(this)>


Was This Post Helpful? 1
  • +
  • -

#3 svpam123  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 47
  • Joined: 01-April 11

Re: javascript function doesn't respond

Posted 09 June 2011 - 08:42 AM

View Postahmad_511, on 09 June 2011 - 02:24 AM, said:

Hi,
I think you forgot to close the onsubmit single qoute;
<form id='form1' name='form1' action='UpdateData.aspx' method='post' onsubmit='return validateForm(this)>


hey
thanks, didn't notice that.
changed it and it actually did make a difference - in my .js file I have after the last if statement, a 'return true;'.
I've added an alert("abc") to it and on submit it actually does show the alert which didn't happen before, but it still doesn't perform any of the validations...

any ideas?
Was This Post Helpful? 0
  • +
  • -

#4 ahmad_511  Icon User is offline

  • MSX
  • member icon

Reputation: 131
  • View blog
  • Posts: 722
  • Joined: 28-April 07

Re: javascript function doesn't respond

Posted 09 June 2011 - 09:24 AM

well,
according to your code it does exactly what is in there.

example
you're testing if the password value is grater than 0 to do the validation right,
what if it's not? try to check if it's not equals to empty string ""
when the user leaves the field empty its value will be an empty string.

note:
are all of these fields optional? cause your validation is performed only when a field has a value,
so if all fields left empty none of your validation codes will get executed and true will return

if it doesn't help, please let us know what is the logic here, what are the fields need to be validated.

Regards
Was This Post Helpful? 1
  • +
  • -

#5 svpam123  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 47
  • Joined: 01-April 11

Re: javascript function doesn't respond

Posted 09 June 2011 - 09:33 AM

View Postahmad_511, on 09 June 2011 - 09:24 AM, said:

well,
according to your code it does exactly what is in there.

example
you're testing if the password value is grater than 0 to do the validation right,
what if it's not? try to check if it's not equals to empty string ""
when the user leaves the field empty its value will be an empty string.

note:
are all of these fields optional? cause your validation is performed only when a field has a value,
so if all fields left empty none of your validation codes will get executed and true will return

if it doesn't help, please let us know what is the logic here, what are the fields need to be validated.

Regards

hey again
yes, none of them are mandatory.
this is actually a form which allows the user to edit his information.
I didn't know how to do an sql query which ignores nulls, so the guys on the ASP forum suggested that I use an if statement to do something like this -
if the field is empty, fetch his old data from the database and insert it. else, use the data from the form.
so I only care about what happens if the user actually enters something. nothing entered = nothing updated in the database.

and thats why the validation should only work if the field isn't empty.
thing is, it doesn't do anything. if I go to the age field and put letters in, it will just submit it (although i'll get an error because the field in the DB is from the data-type int).
same with the other fields... if I insert something to the field so that its bigger than 0, the validation still doesn't work.

things I want to .js file to check for -
passwords matching & greater than 6 characters, email has to include ',' , '@' and greater than 3 characters.
first name and last name fields can't be numbers, and the age field can't be letters.

thank you very much for your attempts to help by the way :)
Was This Post Helpful? 0
  • +
  • -

#6 ahmad_511  Icon User is offline

  • MSX
  • member icon

Reputation: 131
  • View blog
  • Posts: 722
  • Joined: 28-April 07

Re: javascript function doesn't respond

Posted 09 June 2011 - 10:40 AM

IMO a better way to do this is to create some extra functions as bellow:
1- function to trim a given string
2- function to check if given input is a numeric
3- function to check if given input is a string
4- function to check if given string is a valid email address (this will remove the necessary to check for the (@), (.) and the length

and the best way to do this is using Regular Expressions aka Regex
so, here we go:
function trim(str){
	return str.replace(/^\s+|\s+$/g,"");
}

function isNumeric(str){
	var re=/^\d+$/;
	return re.test(str);
}

function isLetters(str){
	var re=/^[A-Za-z]+$/;
	return re.test(str);
}

function isEmail(str){
	var re=/^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/;
	return re.test(str);
}

function validateForm(form1) {

	if (form1.Password.value !="") {
		var pw1=trim(form1.pass2.value);
		var pw2=trim(form1.pass2.value);
		
		if (pw.length == 0) {
			alert("Please validate password");
			return false;
		}
		if (pw1 != pw2) {
			alert("Please enter matching passwords!");
			return false;
		}
		if (pw.length < 6) {
			alert("Passwords are too short!");
			return false;
		}
	}

	if (form1.Email.value !="") {
		var eml=trim(form1.Email.value);

		if (!isEmail(eml)) {
			alert("This is not a valid email");
			return false;
		}
	}

	if (form1.Age.value!= "") {
		var age=trim(form1.Age.value);
		if (!isNumeric(age)) {
			alert("Age must be in numbers!");
			return false;
		}
	}

	if (form1.Fname.value!= "") {
		var fn=trim(form1.Fname.value);
		if (!isLetters(fn)) {
			alert("First name must be in letters!");
			return false;
		}
	}
	
	if (form1.Lname.value!= "") {
		var ln=trim(form1.Lname.value);
		if (!isLetters(ln)) {
			alert("Last name must be in letters!");
			return false;
		}
	}
	
  return true;
}



Note:
to understand how Regex works you can google it and you'll see tons of examples and tutorials
you can check here at w3schools

I hope it helps
Was This Post Helpful? 1
  • +
  • -

#7 svpam123  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 47
  • Joined: 01-April 11

Re: javascript function doesn't respond

Posted 09 June 2011 - 12:39 PM

hey
thanks again, but honestly - my problem isn't really writing the javascript code and validating the fields.
my problem is is that it isn't even working! when I press submit the code doesn't respond...
Was This Post Helpful? 0
  • +
  • -

#8 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6078
  • View blog
  • Posts: 23,546
  • Joined: 23-August 08

Re: javascript function doesn't respond

Posted 09 June 2011 - 01:20 PM

Can you copy/paste the HTML source of the page where this isn't working?
Was This Post Helpful? 0
  • +
  • -

#9 svpam123  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 47
  • Joined: 01-April 11

Re: javascript function doesn't respond

Posted 09 June 2011 - 01:58 PM

View PostJackOfAllTrades, on 09 June 2011 - 01:20 PM, said:

Can you copy/paste the HTML source of the page where this isn't working?

hey
this isn't really HTML source code, but I hope this helps you -

SearchASP.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="SearchASP.aspx.cs" Inherits="_Default" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace = "System.Data.SqlClient" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
    
    
   
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">

    <% 
    
    string UserId = "";
    if (Request.QueryString["SelfEdit"] == "Yes") 
    {
        UserId = (string)(Session["LoggedIn"]); 
    }
    else // 
    {
        UserId = Request.Form["UserId"];
    }
        
        DataSet ds = new DataSet();
        string connStr = @"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\User\Documents\Visual Studio 2010\WebSites\Website3\App_Data\Database.mdf;Integrated Security=True;User Instance=True";
        SqlConnection con = new SqlConnection(connStr);
        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "Select *  from tbl2 where ( UserId = '" + UserId + "')"; 
        cmd.Connection = con;
        con.Open();
        string str = "Information about user " + UserId + ": " + "<br>";
        SqlDataAdapter adapter = new SqlDataAdapter(cmd);
        adapter.Fill(ds, "tbl2");

        if (ds.Tables[0].Rows.Count == 0) 
        {

            string NotFound = "";
            NotFound = "The username " + UserId + " was not found. Please enter a new one.";
            Response.Write(NotFound);
            Response.Write("<script type=\"text/javascript\" > " + "document.location.href = 'SearchHTMLPage.aspx'; " + "</script>");
        }
        else
        {
            
            
            str = str + "First name: " + ds.Tables[0].Rows[0]["Fname"] + "<br>";
            Session["Fname"] = ds.Tables[0].Rows[0]["Fname"]; 
            
            str = str + "Last name: " + ds.Tables[0].Rows[0]["Lname"] + "<br>";
            Session["Lname"] = ds.Tables[0].Rows[0]["Lname"]; 
            
            str = str + "Email: " + ds.Tables[0].Rows[0]["Email"] + "<br>";
            Session["Email"] = ds.Tables[0].Rows[0]["Email"]; 
            
            str = str + "Age: " + ds.Tables[0].Rows[0]["Age"] + "<br>";
            Session["Age"] = ds.Tables[0].Rows[0]["Age"];

            Session["Password"] = ds.Tables[0].Rows[0]["Password"]; 

            Session["Variable"] = ds.Tables[0].Rows[0]["UserId"]; 

            Response.Write(str);
        }
    

       // Session["Variable"] = ID;
%>


 
<br />
<br />
<%
    
    if (Session["LoggedIn"] != null && ((Session["IsAdmin"] != null) || (Request.QueryString["SelfEdit"] == "Yes") || ((string)(Session["LoggedIn"]) == UserId)))
    {
        Response.Write(
            "<script type='text/javascript' src='ValidateData2.js'>" 
            + "</script>"
            +"<form id='form1' name='form1' action='UpdateData.aspx' method='post' onsubmit='return validateForm(this)'>"
            + "First name: "+ "<input id='Fname' name='Fname' type='text'>" 
            + "<br>"
            + "Last name: " + "<input id='Lname' name='Lname' type='text'>"
            + "<br>"
            + "Password: " + "<input id='Password' name='Password' type='password'>"
            + "<br>"
            + "Validate pass: " + "<input id='pass2' name='pass2' type='password'>"
            + "<br>"
            + "Email: " + "<input id='Email' name='Email' type='text'>"
            + "<br>"
            + "Age: " + "<input id='Age' name='Age' type='text'>"
            + "<br>"
            + "<input id='Submit1' type='submit' value='Edit!' />"
            + "</form>"
            );
        if ((Session["IsAdmin"] != null))
        {
            Response.Write("<a href='Delete.aspx'>" +"<input type=button value='Delete User'>" +"</a>");
        }
    }
    
     %>

</asp:Content>



this is the ValidateData2.js file -
function validateForm(form1) {

          if (form1.Password.value > 0) {
              if (form1.pass2.value.length == 0) {
                  alert("Please validate password");
                  return false;
              }
              if (form1.Password.value != form1.pass2.value) {
                  alert("Please enter matching passwords!");
                  return false;
              }
              if (form1.Password.value.length < 6) {
                  alert("Passwords are too short!");
                  return false;

              }
          }

          if (form1.Email.value > 0) {
              if (form1.Email.value.indexOf('@') == -1) {
                  alert("Email must have '@'");
                  return false;
              }
              if (form1.Email.value.indexOf('.') == -1) {
                  alert("Email must have '.'");
                  return false;
              }
              if (form1.Email.value.length < 3) {
                  alert("Please enter a proper email address");
                  return false;
              }
          }

          if (form1.Age.value> 0) {
              if (isNaN(form1.Age) == true) {
                  alert("Age must be in numbers!");
                  return false;
              }
          }

    
          return true;
}


hope this helps you

thanks!
Was This Post Helpful? 0
  • +
  • -

#10 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6078
  • View blog
  • Posts: 23,546
  • Joined: 23-August 08

Re: javascript function doesn't respond

Posted 09 June 2011 - 03:51 PM

I don't know ASP at all, but that's not what I'm talking about. The ASP is rendered as HTML to the browser, which contains the Javascript that was provided. I think we need to see the source code FROM THE BROWSER of the page where this Javascript is supposed to work.
Was This Post Helpful? 1
  • +
  • -

#11 ahmad_511  Icon User is offline

  • MSX
  • member icon

Reputation: 131
  • View blog
  • Posts: 722
  • Joined: 28-April 07

Re: javascript function doesn't respond

Posted 09 June 2011 - 03:52 PM

Ok,
according to your posts I understood that you reach the point where you have the fields and the Edit button right?
did you see any error in the javascript console so far?
can you confirm that the page did load the external javascript ValidateData2.js?
If yes, try to convert the return true at the end of the function I sent to return false and try again (this way the page should not changed to the UpdateData.aspx
did you see any error when clicking the Edit button?
Was This Post Helpful? 1
  • +
  • -

#12 svpam123  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 47
  • Joined: 01-April 11

Re: javascript function doesn't respond

Posted 09 June 2011 - 10:18 PM

hey again
ahmad, I've tried what you suggested again (wrote the whole form again, I think there was a problem there, don't know why...)
and it works :) the .JS file that I first posted here still doesn't (any idea why?) but yours is actually a lot better.
just a couple of questions if you don't mind -
if (pw.length == 0) {
			alert("Please validate password");
			return false;
		}

if (pw.length < 6) {
			alert("Passwords are too short!");
			return false;
		}



I assume you ment pw1 or pw2 right?
anyway changed the fist to pw2 and second to pw1, and besides that it does all the validations (checked them all) except for the
if (pw1 != pw2) {
			alert("Please enter matching passwords!");
			return false;
		}



I can enter 2 different things and it will still submit.

but I assume thats a minor problem compared to the fact I couldn't do any validation with my old code, so thanks a lot :)

can you please explain what you did in the first functions, or maybe refer me to a reading source? this is a website for a school project and I might be asked about these things :)

thanks!

This post has been edited by svpam123: 09 June 2011 - 10:19 PM

Was This Post Helpful? 0
  • +
  • -

#13 ahmad_511  Icon User is offline

  • MSX
  • member icon

Reputation: 131
  • View blog
  • Posts: 722
  • Joined: 28-April 07

Re: javascript function doesn't respond

Posted 10 June 2011 - 03:28 AM

Hi again,

Quote

I assume you ment pw1 or pw2 right?

Well, Yes, I didn't notice that :)

Quote

can enter 2 different things and it will still submit.


That's because I did another mistake
var pw1=trim(form1.pass2.value);



must be
var pw1=trim(form1.Password.value);



about the functions:
what we used here called Regular Expression, and it used in general to match a portion of string or a pattern,
it most used in validating and replacing strings
there are some special characters (Metacharacters), Quantifiers and properties that have a special meaning to the regex object
see w3schools.com and regular-expressions.info

trim function:
we declared the regex object as following:
/^\s+|\s+$/g


this is one way to create a regex object, the other way is by calling the RegExp(pattern,modifiers)
the pattern here is ^\s+|\s+$
the pattern in this way of declaration must starts and ends with forward slash

and the modifier is g (stands for Global), which means search all of the string and don't stop on first occurrence.
^ means the string must starts with the pattern came after.
$ means the string must ends with the pattern came before.
\s matches any white space character.
+ means one or more of pattern came before.
| means or.

so, what is this regular expression saying?
it says: we want to check if a string starts with one or more white space or ends with one or more white space there will be a match.
matched portions of the string will be passed to the replace function
we used the g modifier to make sure that returned matches will not stop on first occurrence, if we removed the g only preceding white spaces will be removed.

finally we do the replacement
str.replace(/^\s+|\s+$/g,"");



in the other functions we didn't replace matched patterns we just check for them, so we used the regex's test() method which returns a Boolean.
the d means digit in the isNumeric function.

you can refer links I provided here or google it to find more about RegExp in javascript.

Hope it helps.

This post has been edited by ahmad_511: 10 June 2011 - 03:42 AM

Was This Post Helpful? 1
  • +
  • -

#14 svpam123  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 47
  • Joined: 01-April 11

Re: javascript function doesn't respond

Posted 10 June 2011 - 04:01 AM

thank you very very much ahmad.
I'm going now so I didn't have a chance to read about the RegExp and what you said deeply, but when I'll come back in a couple of hours I'll read about it.

thanks (:
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1