Web Hosting Talk







View Full Version : ASP code question


Ron
12-07-2002, 12:26 AM
The following code came out of an ASP form mailer. Can anyone tell me how I can revise the code to validate at server-side that the user has entered a valid email address?

strFrom = Request.Form("txtUser.Email")
if Len(strFrom) = 0 then
Response.Write "No email address entered. Please click your browser's back button and type in your email address."
Response.End
end if

For example, if Len(strFrom) does not contain "@" then Response.Write "go back and do it right!"

I guess basically what I am asking is, how do you write "does not contain" in ASP lingo.

Thanks,

Ron

flitcher
12-07-2002, 12:41 AM
If you post in the Programming Forum you may get a response quicker, as most techie's hang out in there. :)

<<MOD NOTE: Thread moved>>

protecweb
12-07-2002, 01:24 PM
Its best to use regular expressions for a proper check. Just looking for an @ is not very thorough. Use this function:

<%
Function isValidEmail(myEmail)
dim isValidE
dim regEx

isValidE = True
set regEx = New RegExp

regEx.IgnoreCase = False

regEx.Pattern = "^[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]$"
isValidE = regEx.Test(myEmail)

isValidEmail = isValidE
End Function
%>

Call it like this:

isValidEmail(Request.Form("Email"))

It will return true or false.

ServerCorps
12-11-2002, 09:32 PM
to extend this to show how it works on a form submit, take this example, extended from the code above to do all this in a single file


<html>
<head>
<title>soooper form mailer</title>
</head>
<%
if request("do_postback") =1 then

dim isValidE
dim regEx
dim invalid_style


isValidE = True
set regEx = New RegExp

regEx.IgnoreCase = False

regEx.Pattern = "^[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]$"
isValidE = regEx.Test(request("myEmail"))

if isValidE then
'send the mail here by whatever means you normally do
'then
response.write "Mail Sent, click <a href="someurl">here</a> to continue"
response.end
else
invalid_style = "color=red"
response.write "invalid email address, please fix"
end if
end if
%>

<input type="hidden" name="do_postback" value="1">
Email Address:<input type="text" style="<%=invalid_style%>" name="myEmail" value="<%=myEmail%>"><br>
Email Subject:<input type="text" name="myEmailSubject"><br>
<a href="thisfilename.asp">Click here to email</a>



this allows validating client entered data on the server on the same page, by using the little "do_postback" hidden input box trick.

This also protects against the form being used to spam since the form must be submitted to itself to send mail.

hth