ASP Form Data Server Side Validation

ASP Best Practices

Use one function to validate multiple form input data types


Date : 2006-04-05
There are a number of arguments for client side form validation:

    1. Less network traffic making for a lighter load on the server.
    2. Faster fulfillment of form requirements.
    3. You can send users funny notices about their inability to fill in a form.


For all of it's advantages though client side validation is not as secure. Of course for a real over-achiever you could use both client and server side validation, or even use AJAX for validation so you can have the security of server side validation and the immediate response of client side validation. I'll try to get an example of AJAX validation up as soon as possible but for now the function below should get you started on creating your own server side validation.




Code:
<%
  Const VALIDATE_EMAIL     = "^[w.-]{1,}@([da-zA-Z-]{1,}.){1,}[da-zA-Z-]+$"
  Const VALIDATE_USZIPCODE = "^d{5}(-d{4})?$"
  Const VALIDATE_USPHONE   = "^(((d{3})s?)|[-.s]?(d{3}[-.s]))d{3}[-.s]d{4}$"
  Const VALIDATE_USSSN     = "^d{3}-d{2}-d{4}$"
  Const VALIDATE_URL       = "^http(s)?://([w-]+.?)+[w-]*(/[w- ./?%=]*)?"
  Const VALIDATE_INTEGER   = "^[0-9]+$"
  Const VALIDATE_FLOAT     = "^[0-9.]+$"
  Const VALIDATE_ALPHA     = "^[a-zA-Zs]+$"
 
  Function validateInput(str, vType)
    dim re
    set re = New RegExp
    with re
      .global     = true
      .ignorecase = true
      .pattern    = vType
    end with
    validateInput = re.test(str)
  End Function

  email   = "editor@bestcodingpractices.com"
  zipcode = "94401"
  phone   = "650 555 5555"
  ssn     = "123-12-1234"
  url     = "http://www.bestcodingpractices.com"
 
  response.write email & " email? " & validateInput(email,VALIDATE_EMAIL) & "<br/>"
  response.write zipcode & " zipcode? " & validateInput(zipcode,VALIDATE_USZIPCODE) & "<br/>"
  response.write phone & " phone?" & validateInput(phone,VALIDATE_USPHONE) & "<br/>"
  response.write ssn & " SSN? " & validateInput(ssn,VALIDATE_USSSN) & "<br/>"
  response.write url & " url? " & validateInput(url,VALIDATE_URL) & "<br/>"
%>


First off, don't make fun of me for lining up my "=" signs, I'm a little anal, but it works for me.

I added in a bit of a test suite for this function so you can tweak with these patterns and add more of your own.

This function will work well in conjunction with the cleanInput(str) function. Whether you clean first or validate first depends on what you're using the data for. If you're going to need to send an email to an email address then you want to validate the end product so clean first then validate.

Feel free to use this function, but send us your patterns, or updates to these patterns, especially I would like to see some international zip code and phone number patterns.

Comments :

BillyDunny 2006-06-27 #13

Why aren't you using the constants as the 2nd param in all the calls validateInput?

  • Search For Articles