Click to See Complete Forum and Search --> : .NET 2.0/Javascript Problem
benopeth
11-28-2008, 06:19 PM
I've been working on a contact form for my website in ASP.NET 2.0 which sends form content to my e-mail address, which is now working perfectly.
I have since begun trying to add Javascript validation to the input fields, preventing empty field submissions, etc. Unfortunately, the ASP is returning an error when I test my validation checks...
"At least one of the From or Sender fields is required, and neither was found."
Now, I know the e-mail field is left blank, otherwise I cannot test my Javascript properly! However, it doesn't seem to be processing it and it goes straight to the ASP error?
Is there something that I should be making sure of when using Javascript in an aspx file?
MikeOS
11-28-2008, 06:34 PM
Are you using the asp.net validation controls? If so (and you should be) you must remember to use the ControlToValidate attribute. It will be best if you post your full code so we can take a look.
benopeth
11-28-2008, 06:43 PM
Thanks for the reply.
Here is my form.
<asp:panel id = "pnl_form" runat = "server">
<form id = "form" runat = "server" onsubmit = "emptyCheck()">
<table id = "contactform">
<tr><td>Name:</td><td><asp:textbox id = "strName" runat = "server"/></td></tr>
<tr><td>Email Address:</td><td><asp:textbox id = "strEmail" name = "strEmail" runat = "server"/></td></tr>
<tr><td>Website:</td><td><asp:textbox id = "strWebsite" runat = "server"/></td></tr>
<tr><td>Subject:</td><td><asp:textbox id = "strSubject" runat = "server"/></td></tr>
<tr><td>Your Message</td><td><asp:textbox id = "strYourMsg" runat = "server" Columns = "30" Rows = "10" TextMode = "MultiLine"/></td></tr>
<tr><td></td><td><asp:button id = "btnSubmit" runat="server" Text="Submit" OnClick="submitQuery" /></td></tr>
</table>
</form>
</asp:panel>
<asp:panel id = "strMessage" runat = "server" visible = "false"><p>Thankyou for your enquiry, I shall be in contact shortly.</p></asp:panel>
Here is my JS to prevent empty fields from being submitted.
function emptyCheck (form)
{
if (document.forms[0].strEmail.value == "") {
alert( "Please enter your email address." );
document.forms[0].strEmail.focus();
return false ;
}
return true ;
}
And here is my ASP...
Sub submitQuery (sender as Object, e as EventArgs)
Dim objMail as New MailMessage()
objMail.To = "yourname@mydomain.com"
objMail.From = strEmail.Text
objMail.BodyFormat = MailFormat.Text
objMail.Priority = MailPriority.Normal
objMail.Subject = strSubject.Text
objMail.Body = "Name: " + strName.Text + vbNewLine + "E-Mail: " + strEmail.text + vbNewLine + "Website: " + strWebsite.text + vbNewLine + "Message: " + strYourMsg.text
SmtpMail.SmtpServer = "smtp.fasthosts.co.uk"
SmtpMail.Send(objMail)
pnl_form.visible = "false"
strMessage.visible = "true"
End Sub
A horrid splat of code I know. I'm a little out of my depth at the moment. I haven't been as I thought it would be best to use JS before submitting to the server? Surely it's possible to use Javascript with ASP.NET 2.0?
MikeOS
11-28-2008, 07:52 PM
Ok, firstly yes you can use JavaScript with ASP.NET but doing things the way you have done them isn't really the way we do them in ASP.NET. You should always take advantage of built in features in order to speed up development time as well as other built in functionality you get for free, which I'll explain later.
Firstly I have removed all of your JavaScript, I have kept 99% of your form but I have added to it and you should keep your server side ASP.NET code. Instead of writing JavaScript to validate a field I have simply used validation controls which will do the work for us. Here is the code (don't worry it isn't as confusing as it may first seem):
<asp:panel id="pnl_form" runat="server">
<form id="form" runat="server">
<table id = "contactform">
<tr><td>Name:</td><td><asp:textbox id ="strName" runat="server"/><asp:RequiredFieldValidator runat="server" ID="rfvstrName" ControlToValidate="strName" Display="Dynamic" ErrorMessage=" You must enter your name" /></td></tr>
<tr><td>Email Address:</td><td><asp:textbox id="strEmail" runat="server"/><asp:RequiredFieldValidator runat="server" ID="rfvstrEmail" ControlToValidate="strEmail" Display="Dynamic" ErrorMessage=" You must enter your email address" /><asp:RegularExpressionValidator runat="server" ID="revEmailPattern" ControlToValidate="strEmail" ValidationExpression="^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$" ErrorMessage=" The email address you have entered is not valid, please enter a valid email address." /></td></tr>
<tr><td>Website:</td><td><asp:textbox id="strWebsite" runat="server"/><asp:RequiredFieldValidator runat="server" ID="rfvstrWebsite" ControlToValidate="strWebsite" Display="Dynamic" ErrorMessage=" You must enter your website address" /></td></tr>
<tr><td>Subject:</td><td><asp:textbox id="strSubject" runat="server"/><asp:RequiredFieldValidator runat="server" ID="rfvstrSubject" ControlToValidate="strSubject" Display="Dynamic" ErrorMessage=" You must enter a subject" /></td></tr>
<tr><td valign="top">Your Message</td><td><asp:textbox id="strYourMsg" runat="server" Columns = "30" Rows = "10" TextMode = "MultiLine"/><asp:RequiredFieldValidator runat="server" ID="rfvstrMessage" ControlToValidate="strYourMsg" Display="Dynamic" ErrorMessage=" You must enter your message" /></td></tr>
<tr><td></td><td><asp:button id="btnSubmit" runat="server" Text="Submit" OnClick="submitQuery" /></td></tr>
</table>
</form>
</asp:panel>
<asp:panel id="strMessage" runat="server" visible="false"><p>Thank you for your enquiry, I shall be in contact shortly.</p></asp:panel>
Consider this line:
<tr><td>Name:</td><td><asp:textbox id ="strName" runat="server"/><asp:RequiredFieldValidator runat="server" ID="rfvstrName" ControlToValidate="strName" Display="Dynamic" ErrorMessage=" You must enter your name" /></td></tr>
This is your TextBox for the users name, you'll see I have added a RequiredFieldValidator control to it. A RequiredFieldValidator does exactly what it says, it ensures the field has data in it before allowing the form to be submitted to the server (the JavaScript is created automatically when the page is built, this is why you don't need to write the JavaScript for it).
The two important attributes are ControlToValidate and ErrorMessage. Now ControlToValidate is used to tell .net which control this validation control is for, in this case it's your strName TextBox, so this is the TextBox it is going to be working with. ErrorMessage is simply the error message you want to display to the user should validation fail, in other words if they left the TextBox empty this message will be displayed to them.
You'll note I've added a RequiredFieldValiator to each of your controls, so in this scenario all controls must be completed before the form can be submitted. Note that I have also added another validation control for your strEmail TextBox called RegularExpressionValidator, here it is again:
<asp:RegularExpressionValidator runat="server" ID="revEmailPattern" ControlToValidate="strEmail" ValidationExpression="^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$" ErrorMessage=" The email address you have entered is not valid, please enter a valid email address." />
Again you'll see the ControlToValidate attribute and it is pointing at your strEmail TextBox. Also you'll see the ErrorMessage attribute. There is the ValidationExpression attribute which looks like I've had a few too many but what it does is simply ensure the user enters a real email address before allowing the form to be submitted.
There are a few more validation controls available to you including a CustomValidator which you can use to write your own JavaScript for instances where the built in validation controls aren't up to the job, but you should always stick with the built in ones when they are. Also there is a ValidationSummary control which can be used to display all the errors in one group anywhere on the page as opposed to next to each control as I have done here.
The advantage to using validation controls are many, firstly, as stated above, you're not reinventing the wheel by doing the all the work yourself when you can just drop these controls in, which speeds up development. Secondly these controls are browser aware so will generate JavaScript specific to the type of browser the user is using, thirdly should the user have a browser that doesn't support JavaScript or has it deactivated no errors will be thrown, and more importantly these controls build the server side validation for you as well, so the should the user bypass client side validation the form will still be validated on the server and refused if it fails validation; and again you haven't had to write a single line of code to do that.
Well I hope that helps, any questions just let me know.
Just realised I didn't add a RegularExpressionValidator to validator the web address the user enters, but there are many online you can find if you need it. Also I'm not sure how to get rid of the smileys that have appeared in the code above so you'll need to change them back to proper code obviously.
MikeOS
11-29-2008, 12:00 PM
One other thing I should have mentioned above was that if you do decide to stick to your original code then all you needed to do to fix it was add the return keyword to the emptyCheck function call like so:
<form id="form" runat="server" onsubmit="return emptyCheck()">
As stated though I don't recommend you use your own JavasScript when the validation controls will do all the work for you.
benopeth
11-29-2008, 12:44 PM
Thanks Mike for all your help!
Whilst I see the benefits of using .NET to perform form validation, it does leave me wondering, what to use Javascript for? I see no need for Javascript where rollovers are concerned, pop-ups/new windows seem to be an ageing practice, etc. I've been trying to learn Javascript over the past few weeks but I find myself questioning how regularly I can adopt it and whether it's worth all the effort?
If you can offer me some re-assurance/decent advice on this I'd be extremely grateful.
MikeOS
11-29-2008, 01:17 PM
Don't panic benopeth, JavaScript is definitely worth learning. Consider the forums on this site, the most popular and active is the JavaScript forum by far.
Apart from that JavaScript is used in DHTML, AJAX and other technologies, even Acrobat uses it. I use to use it for Data Transformation Services in SQL Server so you can see it does have other users outside of the web as well. Also JavaScript conforms to the ECMAScript standard so the syntax will be consistent amongst some other languages such as ActionScript which is used in Flash.
Also ASP.NET doesn't cover everything, I'm frequently writing my own JavaScript. Recently I wrote a delete account page whereby the user had to select on option as the reason why they are deleting their account. Three of the eight options required them to provide more information in a multilne textbox (a textarea), so clearly these textareas were only compulsory if the user selected any or all of those three reasons. I could not use a RequiredFieldValidator as the textareas aren't always going to be required, I didn't want to do postbacks/callbacks (due to the added delay to the user) to determine this so instead I just wrote the whole validation script myself using JavaScript, no validation controls in sight.
Some other things I've done over the last week with JavaScript include:
1)A date of birth validation script.
2)A browser check so I could include a particular feature specific to a browser type.
3)A length check on a couple of multiline TextBoxes (a textarea) to ensure the user stays within character range.
4)A small client side calculator program.
5)A script to decide if I should show or hide a div to the user.
To be honest I could go on and on here with examples. Also should you decide to take up employment as a developer I can guarantee you'll be expected to know it.
Pop up windows in my view are making a bit of a comeback, Ebay uses them, and I've just been on the Royal Mail website and they threw a pop up at me. They are very useful when used properly, I still use them, normally when someone clicks on a help link.
So don't feel disheartened, you do need to know it and it is getting more useful and more powerful all the time.
benopeth
11-29-2008, 01:32 PM
I hear what you're saying so I'll stick with it! I've gathered from several people (including yourself) that it's a core tool in the web developer's kit so I'll take your advice and keep on at it. Didn't realise pop-ups were on the way back, I use no-script in FF so it blocks most things unless I absolutely need to enable something!
Thanks once again for your time and help!
MikeOS
11-29-2008, 09:45 PM
It's a pleasure benopeth, you'll find the developer community is always a very helpful one, there is so much to learn and we will never be experts in all the technologies out there. Check out the MSDN forums they are extremely good when you're stuck, I've used them a lot. Hey it’s always nice when people say thanks, believe me.
Regarding pop-ups it's probably only my opinion that they are making a comeback but there is no harm in using them as long as you do so responsibility. For example I have a sign up page with help links so when the user clicks them I prefer a pop-up rather than navigating to a new page as I want to encourage them to sign up so I try to keep the sign-up page there for them to see at all times - that's an example of using it responsibly, the user doesn’t mind because they have the information they want and all they have to do is close the window and they’re back on my sign up form. It also allays fears of the possibility of moving to a new page clicking back and finding their data has gone and they have to start over completing the form.