Link to home
Start Free TrialLog in
Avatar of Stuperfied
Stuperfied

asked on

Text compare regular expressions field <> "" or chr(13) etc

Hey, I have a message board im making and I need to ensure that the user has entered at least one alphanemerical character or symbol. I remember seeing "[a-zA-Z0-9*.*]" where *.* is the reference for symbols but I cant find out what the *.* should be. Also I am only used to using regular expressions in Perl so I dont know how to use them in VBScript as well. Ive seen some elaborate code which employ's RegExp and all this re.whatever and stuff but I need a simple way of testing the contents of the text area to ensure that the user typed in something without getting into too much robust code. I need something simple like a one liner using InStr or CStr or something. Can someone help me out with this please?

I spent all afternoon trying to complete that regular expression so I think this is worth a few points if someone completes it correctly as per what I remember it was.
Avatar of Stuperfied
Stuperfied

ASKER

will increase the points if someone gets the regular expression correct.
What are the symbols you want to include?
if you want to check for atleast one character that is not numeric you can do this:

Dim cnt, VarToCheck
cnt = 0
VarToCheck = "123R456"

For x = 1 to LEN(MyVar)
   If NOT ISNUMERIC(Mid(MyVar, x, 1)) Then
      cnt = cnt + 1
  End If
Next

If Cnt > 0 THEN
   [You have atleast one char that is not a number]
Else
   [every characters is a number]
End IF

is this what you need?
ah symbols, right, sorry misunderstood...
Yeah, that one is a good one but its a little too robust for my liking. I should explain a bit better I think. I have a reply page for my message board and someone suggested using the trim function to make sure people couldnt submit a blank message. I did that but however realized that it doesnt pick up on carriage returns, I was able to simply hit enter a few times and submit a blank message. I want to leave no room for error and be sure that the message contains at least one letter, number or symbol without having to use a whole page of code.

I want something simple like:
[Code]
If InStr(1, Trim(Request.Form("body")), "[a-zA-Z0-9]", 1) >= 1 Then
' They typed something (other than enter or space etc..) process form
Else
' Message is blank do not process form
[/Code]

I dont even know if the formating of that statement is correct and suspect that the syntax is incorrect but I want it to include all symbols but not special characters in the regular expression as well as the alphanumeric characters.

The "a-z" represents all lower case letters and the "A-Z" represents all upper case letters whilst the "0-9" represents all numbers. There is also one of the same format that represents all characters such as "^-$" or something but I cant remember what it is.

So what I need is a simple function which will search a text area for alphanumeric characters and symbols. Im not very good at explaining things but I hope ive done well enough for you to understand what I mean.

Thanks in advance.
Edit: same format that represents all characters such
*same format that represents all ^symbols such
You can do a regular expression like:

a-zA-Z0-9\s

which will allow all alphanumeric and spaces (including tabs, etc)...

a good resource is: http://www.regexplib.com/Default.aspx

The regular expression for all non-white space is:

\S

Which kills off tabs, form feeds, carriage returns, etc...

What you probably want to do is something like:

[a-zA-Z0-9\x20]+

Which will match alpha numerics, and spaces (hex 20) at least one occurrence.

Another good resource:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/script56/html/js56jsgrpregexpsyntax.asp
Thanks for your quick reply. Unfortunately the \s will not do as I want to make sure that the user didnt simply hit space or enter and then submit their message. I want to make sure that their message contains at least one letter, number or symbol before it is saved. Maybe a-zA-Z0-9\S is what I need? Or is it enough to just have \S ? I need to make sure that users are not submitting blank messages on the message board. Also, what function would I use (without getting too robust)?
I guess you could run a reg exp on the string, removing all white space characters (\s), and then check the 'len' to see if it's above 1.

Code goes something like:

Dim regEx
Set regEx = New RegExp
regEx.Pattern = "\s"
regEx.IgnoreCase = True
regEx.Global = True

sCheckString = regEx.Replace(sInputString, "")
Set regEx = Nothing

If Len(sCheckString) < 2 Then .... Output some message saying 'Oi post something proper'
[Quote]
Dim regEx
Set regEx = New RegExp
regEx.Pattern = "\s"
regEx.IgnoreCase = True
regEx.Global = True
Set regEx = Nothing
[/Quote]

So what your ultimately saying is that a Regular Expression in VBScript, requires a supporting function?
Stuperfied...

"Unfortunately the \s will not do as I want to make sure that the user didnt simply hit space or enter and then submit their message."

It is for testing input then you just test the results.

The idea is to take the user back to the input form if your validation test fails.  You can either test for only valid characters or test for invalid characters, strip either out and then branch accordingly.  If the test fails, report the error and return the user to the input form.  If the test passes, proceed.

While \s will filter all tabs, returns, new lines, vertical tabs and form feeds, it will not filter out all whitespace characters, like alt+255.

You could use: [  \t\r\n\v\f] where the second whitespace character is alt+255 or use:

\s|[ ] where the whitespace character is alt+255.

These are probably the only valid characters you want:

abcdefghijklmnopqrstuvwxyz!"#$%&'()*+'-./:;<=>?@[\]&_`{|}~

Which you could filter using:

\w|[!\"#$%&'()*+'-./:;<=>\?@\[\\\]\&`\{\|\}~]

It might be easier to test the ascii value using the range 32-126, which is what these represent.

I would eliminate the whitespace characters and then test the length.

function testChars(str)
  dim re, strTemp
  set re = new regExp
  re.Pattern = "\s|[ ]"
  re.global = true
  re.ignoreCase = true
  strTemp = re.replace(str,"")
  if len(strTemp) > 0 then
    testChars = true
  else
    testChars = false
  end if
  set re = nothing
end function

I think you have more than one issue but this can get you at least one valid character.  I would also validate email accounts and only allow validated users, logged in, to post.  However, those are separate issues.

My test page:
http://kiddanger.com/lab/ee/validchars.asp
VBScript is different than javascript/Perl in this regard.
Would I not then also have to eliminate html white space special characters such as &nbsp;?
&nbsp; entered into a text input form field will be seen as a literal if you encode it.

strTest = Server.HTMLEncode(Request.Form("ichar"))

You can try it on my test page.
When you encode you have to modify the function because an alt+255 will be encoded as an &nbsp; which is an HTML code of &#160;.  You will no longer get the alt+255 unencoded so you can change your regular expression to just test for spaces, as I am converting any &#160; to spaces first.

Here is the mod:

function testChars(str)
  dim re, strTemp
  set re = new regExp
  re.Pattern = "&#160;"
  re.global = true
  re.ignoreCase = true
  strTemp = re.Replace(str," ")
  re.Pattern = "\s"
  strTemp = re.replace(strTemp,"")
  if len(strTemp) > 0 then
    testChars = true
  else
    testChars = false
  end if
  set re = nothing
end function
I didnt even realize you could do that, does that have any effect on anything other than alt+255 and html code?
I have to go to work now so I might not reply for a while but will be back on tonight.
\s looks for spaces, tabs, returns, new lines, vertical tabs and form feeds.  alt+255 is a whitespace character in the extended part of ascii.  Using SERVER.HTMLEncode will convert it to a &nbsp; but as &#160;.  All entries of &... anything will be encoded so they will effectively be a literal, so & will be converted to &amp;.

This routine is just to strip out whitespace characters i.e. any character not visible in a browser, although it may be listed in the source.
Sorry for the wait, I finally got a chance to get on here and reply. This does seem like the best solution, I can re-write some of the other code to use this as well and put in a global variable to hold the result for the other functions which also rely on the same test, which will make it smaller, faster and cleaner. I dont have time at the moment to try it out because its 23:52 here at the moment but I will try to get some time and give it a go tomorrow night after work.

I dont know what the going rate is for points around here but I only have 455 so if you want some points I guess I could give you 150 of them, let me know if you want them. I think I should probably keep the other 300 odd for any future questions I might have.

Well im off to bed, catch you tomorrow sometime hopefully.
Stuperfied...

The question shows 50 points.  I see no reason why you need to offer more.  I've never asked a question so I really don't know how that part works.  Whatever you want to do is fine with me.
When I type "&nbsp;" into any field the following equates to true but it should equate to false and prevent the form from being submitted. Can you see anything that I did wrong?

[Code]
'Confirm string contents
function testChars(str)
  dim re, strTemp
  set re = new regExp
  re.Pattern = "&#160;"
  re.global = true
  re.ignoreCase = true
  strTemp = re.Replace(str," ")
  re.Pattern = "\s"
  strTemp = re.replace(strTemp,"")
  if len(strTemp) > 0 then
    testChars = true
  else
    testChars = false
  end if
  set re = nothing
end function

Dim MM_usernameContentTestResult
Dim MM_bodyContentTestResult
MM_usernameContentTestResult = false
MM_bodyContentTestResult = false
If (CStr(Request("MM_insert")) = "form1") Then
  MM_usernameContentTestResult = testChars(Server.HTMLEncode(CStr(Request.Form("username"))))
  MM_bodyContentTestResult = testChars(Server.HTMLEncode(CStr(Request.Form("body"))))
End If

If (CStr(Request("MM_insert")) = "form1") and MM_bodyContentTestResult = true Then
[/Code]
When I enter "&nbsp;" into your test page, it also accepts it and outputs true.
It outputs true but shows it as a literal.  It does not show a blank space.
ASKER CERTIFIED SOLUTION
Avatar of kiddanger
kiddanger
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I need to get rid of anything the human eye cannot see and then if there is anything left then the message is allowed.
Actually I think im going about this the wrong way.
"&nbsp;" and any other script characters typed as text should appear as text in the users browser when viewing the resulting post.
So if I press space " " or enter "
" It should appear as such but a post made up completely of invisible characters such as " " or enter "
" should not be allowed.

The end result that I am trying to achieve is simply to make sure that my users can post any content that they want but prevent it from executing and make sure that the posts do not appear empty. Just like in this Experts Exchange message board.
You only need to avoid posts that ONLY contain invisible characters and it's a good idea to render HTML off, as most forums do.

So, test for the invisible characters and put everything else in <pre> </pre> and you have accomplished your goal.
The sample code I have supplied does that right now.

You can offer what's called Forum code, but that's more work.

Ex. [red]This text is red[/red] would result in <span style="color: red">This text is red</span>
Yeah I will want to offer Forum code but not yet, I want to make sure all posts are legal first.
Ok, I put that server.htmlencode on the reply and vew posts pages and now it works fine. So why do I need to use pre? what does it do other than specify that the following text is preformatted?

If your interested in taking a look: http://www.killercomputers.com.au/messageboard/
You should only use <pre> if you're not going to strip out HTML code and offer Forum code.  This will render all HTML code as literal.
Ok, looks like its working ok now. Will let you know if there are any problems with it. Will also probably post again to find out about how to do that forum code too.

Thanks again for your help.
Thanks Stuperfied.
This code still allows me to enter a post filled with carriage returns for some reason, thats not right is it?
No sir.  Can you show your current code?
It was allowing people to post a blank space as their message and their username so I had to add the trim function to it.

[Code]
'Confirm string contents
function testChars(str)
  dim re, strTemp
  set re = new regExp
  re.Pattern = "&#160;"
  re.global = true
  re.ignoreCase = true
  strTemp = re.Replace(str," ")
  re.Pattern = "\s"
  strTemp = re.replace(strTemp,"")
  if len(strTemp) > 0 then
    testChars = true
  else
    testChars = false
  end if
  set re = nothing
end function

Dim MM_usernameContentTestResult
Dim MM_bodyContentTestResult
MM_usernameContentTestResult = false
MM_bodyContentTestResult = false
If (CStr(Request("MM_insert")) = "form1") Then
  MM_usernameContentTestResult = testChars(Server.HTMLEncode(Trim(CStr(Request.Form("username")))))
  MM_bodyContentTestResult = testChars(Server.HTMLEncode(Trim(CStr(Request.Form("body")))))
End If

' boolean to abort record edit
MM_abortEdit = false

' query string to execute
MM_editQuery = ""
%>
<%
' *** Insert Record: set variables

If (CStr(Request("MM_insert")) = "form1") and MM_bodyContentTestResult = true Then
[/Code]
I'm not using Trim and spaces only are filtered and fail the test.  I need to see the code where you use the input fields content.  If you'll notice, I'm creating a new test variable with the encoded input but when I use the input field content, it is only if the test passes.
[Code]
<!-- reply.asp -->
<%@LANGUAGE="VBSCRIPT" CODEPAGE="1252"%>

<%
' *** Edit Operations: declare variables

Dim MM_editAction
Dim MM_abortEdit
Dim MM_editQuery
Dim MM_editCmd

Dim MM_editConnection
Dim MM_editTable
Dim MM_editRedirectUrl
Dim MM_editColumn
Dim MM_recordId

Dim MM_fieldsStr
Dim MM_columnsStr
Dim MM_fields
Dim MM_columns
Dim MM_typeArray
Dim MM_formVal
Dim MM_delim
Dim MM_altVal
Dim MM_emptyVal
Dim MM_i

Dim MM_messageboard_STRING
MM_messageboard_STRING = "Driver={Mysql}; Server=example.com.au; Database=example_com_au_messageboard; UID=exampleID; PWD=examplePass"

MM_editAction = CStr(Request.ServerVariables("SCRIPT_NAME"))
If (Request.QueryString <> "") Then
  MM_editAction = MM_editAction & "?" & Request.QueryString
End If

'Confirm string contents
function testChars(str)
  dim re, strTemp
  set re = new regExp
  re.Pattern = "&#160;"
  re.global = true
  re.ignoreCase = true
  strTemp = re.Replace(str," ")
  re.Pattern = "\s"
  strTemp = re.replace(strTemp,"")
  if len(strTemp) > 0 then
    testChars = true
  else
    testChars = false
  end if
  set re = nothing
end function

Dim MM_usernameContentTestResult
Dim MM_bodyContentTestResult
MM_usernameContentTestResult = false
MM_bodyContentTestResult = false
If (CStr(Request("MM_insert")) = "form1") Then
  MM_usernameContentTestResult = testChars(Server.HTMLEncode(Trim(CStr(Request.Form("username")))))
  MM_bodyContentTestResult = testChars(Server.HTMLEncode(Trim(CStr(Request.Form("body")))))
End If

' boolean to abort record edit
MM_abortEdit = false

' query string to execute
MM_editQuery = ""
%>
<%
' *** Insert Record: set variables

If (CStr(Request("MM_insert")) = "form1") and MM_bodyContentTestResult = true Then

  MM_editConnection = MM_messageboard_STRING
  MM_editTable = "post"
  MM_editRedirectUrl = "posts.asp"
  MM_fieldsStr  = "body|value|board_id|value|username|value"
  MM_columnsStr = "body|',none,''|board_id|none,none,NULL|username|',none,''"

  ' create the MM_fields and MM_columns arrays
  MM_fields = Split(MM_fieldsStr, "|")
  MM_columns = Split(MM_columnsStr, "|")
 
  ' set the form values
  For MM_i = LBound(MM_fields) To UBound(MM_fields) Step 2
    MM_whatever = Replace(CStr(server.HTMLEncode(Request.Form(MM_fields(MM_i)))), "<", "&lt;")
    MM_whatever = Replace(MM_whatever, ">", "&gt;")
      'MM_whatever = Replace(MM_whatever, chr(13), vbCr)
      If MM_fields(MM_i) = "username" and Session("MM_Username") <> "" Then      
      MM_whatever = Session("MM_Username")
      End If
    MM_fields(MM_i+1) = MM_whatever
  Next

  ' append the query string to the redirect URL
  If (MM_editRedirectUrl <> "" And Request.QueryString <> "") Then
    If (InStr(1, MM_editRedirectUrl, "?", vbTextCompare) = 0 And Request.QueryString <> "") Then
      MM_editRedirectUrl = MM_editRedirectUrl & "?" & Request.QueryString
    Else
      MM_editRedirectUrl = MM_editRedirectUrl & "&" & Request.QueryString
    End If
  End If
End If
%>
<%
' *** Insert Record: construct a sql insert statement and execute it

Dim MM_tableValues
Dim MM_dbValues

If (CStr(Request("MM_insert")) <> "") AND MM_bodyContentTestResult = true Then
If Session("MM_Username") <> "" OR MM_usernameContentTestResult = true Then

  ' create the sql insert statement
  MM_tableValues = ""
  MM_dbValues = ""
  For MM_i = LBound(MM_fields) To UBound(MM_fields) Step 2
    MM_formVal = MM_fields(MM_i+1)
    MM_typeArray = Split(MM_columns(MM_i+1),",")
    MM_delim = MM_typeArray(0)
    If (MM_delim = "none") Then MM_delim = ""
    MM_altVal = MM_typeArray(1)
    If (MM_altVal = "none") Then MM_altVal = ""
    MM_emptyVal = MM_typeArray(2)
    If (MM_emptyVal = "none") Then MM_emptyVal = ""
    If (MM_formVal = "") Then
      MM_formVal = MM_emptyVal
    Else
      If (MM_altVal <> "") Then
        MM_formVal = MM_altVal
      ElseIf (MM_delim = "'") Then  ' escape quotes
        MM_formVal = "'" & Replace(MM_formVal,"'","''") & "'"
      Else
        MM_formVal = MM_delim + MM_formVal + MM_delim
      End If
    End If
    If (MM_i <> LBound(MM_fields)) Then
      MM_tableValues = MM_tableValues & ","
      MM_dbValues = MM_dbValues & ","
    End If
    MM_tableValues = MM_tableValues & MM_columns(MM_i)
    MM_dbValues = MM_dbValues & MM_formVal
  Next
  MM_editQuery = "insert into " & MM_editTable & " (" & MM_tableValues & ") values (" & MM_dbValues & ")"

  If (Not MM_abortEdit) Then
    ' execute the insert
    Set MM_editCmd = Server.CreateObject("ADODB.Command")
    MM_editCmd.ActiveConnection = MM_editConnection
    MM_editCmd.CommandText = MM_editQuery
    MM_editCmd.Execute
    MM_editCmd.ActiveConnection.Close

    If (MM_editRedirectUrl <> "") Then
      Response.Redirect(MM_editRedirectUrl)
    End If
  End If
End If
End If
%>
<%
Dim rsPosts__MMColParam
rsPosts__MMColParam = "1"
If (Request.QueryString("board_id") <> "") Then
  rsPosts__MMColParam = Request.QueryString("board_id")
End If
%>
<%
Dim rsPosts
Dim rsPosts_numRows

Set rsPosts = Server.CreateObject("ADODB.Recordset")
rsPosts.ActiveConnection = MM_messageboard_STRING
rsPosts.Source = "SELECT * FROM post WHERE board_id = " + Replace(rsPosts__MMColParam, "'", "''") + ""
rsPosts.CursorType = 0
rsPosts.CursorLocation = 2
rsPosts.LockType = 1
rsPosts.Open()

rsPosts_numRows = 0
%>
<%
Dim rsBoards__MMColParam
rsBoards__MMColParam = "1"
If (Request.QueryString("board_id") <> "") Then
  rsBoards__MMColParam = Request.QueryString("board_id")
End If
%>
<%
Dim rsBoards
Dim rsBoards_numRows

Set rsBoards = Server.CreateObject("ADODB.Recordset")
rsBoards.ActiveConnection = MM_messageboard_STRING
rsBoards.Source = "SELECT * FROM board WHERE board_id = " + Replace(rsBoards__MMColParam, "'", "''") + ""
rsBoards.CursorType = 0
rsBoards.CursorLocation = 2
rsBoards.LockType = 1
rsBoards.Open()

rsBoards_numRows = 0
%>
<script language="JavaScript" type="text/javascript">
<!--
function MM_reloadPage(init) {  //reloads the window if Nav4 resized
  if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
    document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
  else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}
MM_reloadPage(true);

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_showHideLayers() { //v6.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
    obj.visibility=v; }
}
//-->
</script>
<html>
<head>
<title>Reply</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link href="../scripts/styles.css" rel="stylesheet" type="text/css">
</head>

<body bgcolor="#FFFFEA">
<div id="main" style="position: relative; visibility: visible">
  <form name="form1" method="POST" action="<%=MM_editAction %>">
    <table border="0">
      <tr>
        <td> <p><b>This thread allows anonymous posting but you will still be<br>
            required to enter an anonymous username for your post.<br>
            Please post your reply in the form below.</b></p>
          <table class="mastertable" width="800" border="0" cellspacing="0" cellpadding="0">
            <tr>
              <td class="headtable" colspan="2" valign="top"><font color="#FFFFFF"<b>Replying
                To: <%=(rsBoards.Fields.Item("name").Value)%></b></font></td>
            </tr>
            <tr>
              <td class="subtable" colspan="2">&nbsp;</td>
            </tr>
            <% If Session("MM_Username") = "" Then %>
            <tr>
              <td class="lefttitletable" width="155" valign="top"><b>Username:</b></td>
              <td class="righttitletable" width="645"><input name="username" type="text" id="username" size="40" maxlength="50">
                <% If (CStr(Request("MM_insert")) <> "") Then
                If Session("MM_Username") = "" and MM_usernameContentTestResult = false Then
  response.Write("<font color='red'><b>* You must enter an anonymous username to continue.<b></font>")
End If
End If %> </td>
            </tr>
            <% End If %>
            <tr>
              <td class="leftcontenttable" valign="top">&nbsp;</td>
              <td class="rightcontenttable" valign="top">&nbsp;</td>
            </tr>
            <tr>
              <td class="leftcontenttable" valign="top"><b>Message Body:</b></td>
              <td class="rightcontenttable" valign="top"><textarea name="body" cols="80" rows="15" id="body">Unspecified</textarea>
                <% If (CStr(Request("MM_insert")) <> "") Then
                If MM_bodyContentTestResult = false Then
  response.Write("<font color='red'><b>* You must enter a message to continue.<b></font>")
End If
End If
%> </td>
            </tr>
            <tr>
              <td class="actionbarlefttable">&nbsp;</td>
              <td class="actionbarrighttable">&nbsp;</td>
            </tr>
            <tr>
              <td class="foottable" colspan="2">&nbsp; <input type="hidden" name="board_id" id="board_id" value="<%=rsPosts__MMColParam%>"></td>
            </tr>
          </table></td>
      </tr>
      <tr>
        <td><div align="right">
            <input name="Submit" type="submit" id="Submit" value="Post Reply" onClick="MM_showHideLayers('main','','hide');">
            <input type="button" name="Submit2" value="Preview Message">
          </div></td>
      </tr>
    </table>
    <input type="hidden" name="MM_insert" value="form1">
  </form>
</div>
</body>
</html>
<%
rsPosts.Close()
Set rsPosts = Nothing
%>
<%
rsBoards.Close()
Set rsBoards = Nothing
%>
[/Code]