Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-10 of 15 total  RSS 

APS Form Validation

ASP Form validation (including required and optional fields and reverse MX lookup for e-mail address - not sure why)

   1  
   2  <head>
   3    <title>Implemented Form Validation</title>
   4    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
   5  </head>
   6  <style>
   7    .errorMessage {
   8      color : #F00;
   9    }
  10    .errorItem {
  11      background : #F99;
  12    }
  13  </style>
  14  <body>
  15  <!--Settings-->
  16  <%
  17  '=================================
  18  'All fields are acted as required
  19  ' except those the NAME of which
  20  ' is in this string variable:
  21  '=================================
  22  exceptions = Array("address")
  23  
  24  '=================================
  25  'NAME of the e-mail field is 
  26  ' stored in this string variable:
  27  '=================================
  28  emailField = "email"
  29  
  30  '=================================
  31  'Variables
  32  '=================================
  33  dim errorMessage, badItem, inputArray() : badItem=-1
  34  redim inputArray(50,2)
  35  
  36  '=================================
  37  'Get all what is submitted
  38  '=================================
  39  IF request.Form.Count > 0 THEN
  40    execute("const numberOfFields =" & request.Form.Count)
  41    execute("redim inputArray("&numberOfFields&",2)")
  42    FOR i = 1 TO request.Form.Count
  43      inputArray(i,1) = request.Form.Key(i)
  44      inputArray(i,2) = request.Form.Item(i)
  45    NEXT
  46    validate
  47  ELSEIF request.QueryString.Count > 0 THEN
  48    execute("const numberOfFields =" & request.QueryString.Count)
  49    execute("redim inputArray("&numberOfFields&",2)")
  50    FOR i = 1 TO request.QueryString.Count
  51      inputArray(i,1) = request.QueryString.Key(i)
  52      inputArray(i,2) = request.QueryString.Item(i)
  53    NEXT
  54    validate
  55  END IF
  56  
  57  SUB validate
  58    '=================================
  59    'Check for empty fields
  60    '=================================
  61    FOR i = 1 TO numberOfFields
  62      isException = False
  63      IF inputArray(i,2)="" THEN
  64        FOR j = 0 to UBound(exceptions)
  65          IF inputArray(i,1) = exceptions(j) THEN isException = TRUE
  66        NEXT
  67        IF NOT isException THEN
  68          badItem = i
  69          errorMessage = "At least one of the required fields is left empty."
  70          EXIT SUB
  71        END IF
  72      END IF
  73      isException = False
  74    NEXT
  75  
  76    '=================================
  77    'Check email address for basic
  78    ' errors
  79    '=================================
  80    FOR i = 1 TO numberOfFields
  81      IF emailField=inputArray(i,1) THEN
  82        validationResult = validateEmail(inputArray(i,2))
  83        IF validationResult <> "" THEN
  84          errorMessage = validationResult
  85          badItem = i
  86        END IF
  87      END IF
  88    NEXT
  89  END SUB
  90  
  91  FUNCTION validateEmail(strAddress)
  92    IF InStr(strAddress,"@") < 2 THEN
  93      validateEmail = "Email address must contain ""@"" sign."
  94    ELSEIF InStr(Right(strAddress,Len(strAddress)-InStr(strAddress,"@")),".") < 2 OR InStr(Right(strAddress,Len(strAddress)-InStr(strAddress,"@")),".") = Len(strAddress)-InStr(strAddress,"@") THEN
  95      validateEmail = "Email address must contain ""."" sign."
  96    ELSE
  97      host = Right(strAddress,Len(strAddress)-InStr(strAddress,"@"))
  98      IF NOT MXLookUp(host) THEN validateEmail = "Bad email address."
  99    END IF
 100  END FUNCTION
 101  
 102  FUNCTION MXLookUp(host)
 103    MXLookUp = False
 104    Dim objXMLHTTP,strResult
 105    Set objXMLHTTP = Server.CreateObject("Microsoft.XMLHTTP")
 106    objXMLHTTP.Open "Get", _
 107    "http://examples.softwaremodules.com/IntraDns.asp?domainname=" & host & "&Submit=Submit&t_mx=1", False
 108    objXMLHTTP.Send
 109    strResult = objXMLHTTP.ResponseText
 110    strResult = Mid(strResult,InStr(strResult,"(MX) for <strong>"),100)
 111    strResult = Mid(strResult,Instr(strResult,"</strong>. Items Returned: <strong>")+35,1)
 112    IF CInt(strResult) > 0 THEN 
 113      MXLookUp = TRUE
 114    ELSE
 115      MXLookUp = FALSE
 116    END IF
 117  END FUNCTION 
 118  %>
 119  <h2>Form Validator</h2>
 120  <%
 121  IF errorMessage<>"" THEN
 122    %>
 123    <p class="errorMessage">There was an error with your form: <b><%=errorMessage%></b></p>
 124    <%
 125  ELSEIF request.form.count = 0 THEN
 126    %>
 127    <h3>Please fill in the form:</h3>
 128    <%
 129  ELSE
 130    %>
 131    <h3>Thank you!</h3>
 132    </body>
 133    </html>
 134    <%
 135    response.End
 136  END IF
 137  %>
 138  
 139  <form action="default.asp" method="post">
 140  
 141  <p>Name: <font color="#FF0000">*</font>
 142  <input name="name" type="text" id="name" value="<%=inputArray(1,2)%>" <%IF badItem=1 THEN response.write "class=""errorItem"""%>/>
 143  </p>
 144  
 145  <p>Address: 
 146  <input name="address" type="text" id="address" value="<%=inputArray(2,2)%>" <%IF badItem=2 THEN response.write "class=""errorItem"""%>/>
 147  </p>
 148  
 149  <p>Email: <font color="#FF0000">*</font>
 150  <input name="email" type="text" id="email" value="<%=inputArray(3,2)%>" <%IF badItem=3 THEN response.write "class=""errorItem"""%>/>
 151  </p>
 152  
 153  <p> 
 154  <input type="submit" value="Submit" />
 155  </p>
 156  
 157  </form>
 158  
 159  </body>

jquery validation not clearing errors example

// jquery validation example not clearing error messages

   1  
   2  <html>
   3  <head>
   4    <script src="http://code.jquery.com/jquery-latest.js"></script>
   5  <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script>
   6  
   7    <script type="text/javascript">
   8    $(document).ready(function(){  
   9      $("#command").validate({
  10        errorPlacement: function(label, element) {        
  11          //$(element).prev(".error").replaceWith("");
  12          label.insertBefore( element );
  13        },    
  14      
  15        rules: {      
  16          "profileBean.loginEmail": {
  17                  required: true,
  18                  minlength: 5,
  19  				email:true
  20              },    
  21          "password": {
  22          					required:true,
  23          					minlength:5
  24          			},
  25  		"passconfirm":{
  26  		                    required:true,
  27  		                    minlength:5,
  28  		                    equalTo:"#password"
  29  		}
  30        },
  31        messages:{
  32            "profileBean.loginEmail":{
  33                                required:"Email must be supplied",
  34                                minlength:"specify at least 5 characters",
  35            }
  36         }
  37      });  
  38    });
  39    </script>  
  40    
  41  </head>
  42  <body>
  43    
  44  
  45     <table >
  46  
  47          <form id="command" name="registerForm" action="www.cnn.com" method="POST">
  48      <tr><td align="center"></td></tr>                      
  49      <tr>                
  50          <td ><span class="spanlabel">Email Address</span><br />
  51          <input id="profileBean.loginEmail" name="profileBean.loginEmail"  type="text" value=""/></td>        
  52          </tr>
  53      <tr>
  54  
  55          <td ><span class="spanlabel">Password</span><br />
  56          <input id="password" name="profileBean.password" type="password" value=""/></td>        
  57          </tr>
  58  
  59      <tr>
  60          <td ><span class="spanlabel">Re-enter password</span><br />
  61          <input type="password" id="passconfirm" name="passconfirm" /></td>
  62          </tr>
  63  
  64  
  65      <tr>
  66          <td >
  67          <input type="submit" name="submit" /></td>
  68          </tr>
  69          </form>
  70          
  71       
  72  </table>
  73  
  74  </body>
  75  </html>

Rails validation for Phone

   1  
   2    validates_length_of :phone, :is => 10, :message => 'must be 10 digits, excluding special characters such as spaces and dashes. No extension or country code allowed.', :if => Proc.new{|o| !o.phone.blank?}
   3    validates_length_of :fax, :is => 10, :message => 'must be 10 digits, excluding special characters such as spaces and dashes. No extension or country code allowed.', :if => Proc.new{|o| !o.fax.blank?}

Mark directories to be deleted based on their date-stamp

This Ruby code selects file directories which are older than a certain date and outputs an XML file naming all the directories to be removed. It does this by reading a directory listing formatted within the XML file 'dir.xml', all directories are named by a date-stamp, which is used to determine if the directory should be removed.

This example is used to maintain the webcamera (named 'pear') which saves it's images to a date-stamped directory daily. Any directory which is older than 14 days will be marked for deletion.

   1  
   2    def directory_housekeeping()
   3      lifespan = 14
   4      format_mask = 'm_d_y'
   5      separator = format_mask.match(/[\_*\-]/).to_s
   6      
   7      earliest_date = Time.now + (60 * 60 * 24) * -lifespan
   8      cut_off_date = Date.new(y=earliest_date.year,m=earliest_date.month,d=earliest_date.day)
   9          
  10      a_format = Array.new
  11      a_format[0] = format_mask.match(/^[y,m,d]*/).to_s
  12      a_format[1] = format_mask.match(separator + '[y,m,d]*').to_s.gsub(separator,'')
  13      a_format[2] = format_mask.match('[y,m,d]$').to_s
  14      
  15      file = File.new('../housekeeping/webcam_pear/dir.xml')
  16      ddoc = REXML::Document.new(file)
  17      file.close
  18      
  19      file_delete = File.new('../housekeeping/webcam_pear/files2delete.xml', 'w')
  20      doc_delete = Document.new()
  21      doc_delete.add_element('files')
  22      
  23      ddoc.root.elements.each('file') do |file_node|
  24        sfile = file_node.text
  25        idate = Array.new
  26        idate[0] = sfile.match(/^\d*/).to_s.to_i
  27        idate[1] = sfile.match(/\_\d*/).to_s.gsub(separator,'').to_i
  28        idate[2] = sfile.match(/\_\d*\d$/).to_s.gsub(separator,'').to_i
  29  
  30        h = Hash.new
  31        0.upto(2) {|i| h[a_format[i]] = idate[i]}
  32  
  33        file_date = Date.new(y=h['y'], m=h['m'], d=h['d'])
  34  
  35        if file_date < cut_off_date
  36          o_file2delete = Element.new('file')
  37          o_file2delete.text = file_date.strftime(dformat)
  38          doc_delete.root.add_element o_file2delete
  39        end
  40      end
  41      file_delete.puts doc_delete
  42    end
  43  


file: dir.xml
   1  
   2  <dir>
   3    <file>11_4_2007</file>
   4    <file>11_5_2007</file>
   5    <file>11_6_2007</file>
   6    <file>11_7_2007</file>
   7    <file>11_8_2007</file>
   8    <file>11_9_2007</file>
   9    <file>12_10_2007</file>
  10    <file>12_11_2007</file>
  11    <file>12_1_2007</file>
  12    <file>12_12_2007</file>
  13    <file>12_13_2007</file>
  14    <file>12_14_2007</file>
  15    <file>12_15_2007</file>
  16    <file>12_16_2007</file>
  17    <file>12_17_2007</file>
  18    <file>12_18_2007</file>
  19    <file>12_19_2007</file>
  20    <file>12_20_2007</file>
  21    <file>12_21_2007</file>
  22    <file>12_2_2007</file>
  23    <file>12_22_2007</file>
  24    <file>12_23_2007</file>
  25    <file>12_24_2007</file>
  26    <file>12_25_2007</file>
  27    <file>12_26_2007</file>
  28    <file>12_27_2007</file>
  29    <file>12_28_2007</file>
  30    <file>12_3_2007</file>
  31    <file>12_4_2007</file>
  32    <file>12_5_2007</file>
  33    <file>12_6_2007</file>
  34    <file>12_7_2007</file>
  35    <file>12_8_2007</file>
  36    <file>12_9_2007</file>
  37   </dir>

file: files2delete.xml
   1  
   2  <files>
   3    <file>11_4_2007</file>
   4    <file>11_5_2007</file>
   5    <file>11_6_2007</file>
   6    <file>11_7_2007</file>
   7    <file>11_8_2007</file>
   8    <file>11_9_2007</file>
   9    <file>12_10_2007</file>
  10    <file>12_11_2007</file>
  11    <file>12_1_2007</file>
  12    <file>12_12_2007</file>
  13    <file>12_13_2007</file>
  14    <file>12_14_2007</file>
  15    <file>12_15_2007</file>
  16    <file>12_2_2007</file>
  17    <file>12_3_2007</file>
  18    <file>12_4_2007</file>
  19    <file>12_5_2007</file>
  20    <file>12_6_2007</file>
  21    <file>12_7_2007</file>
  22    <file>12_8_2007</file>
  23    <file>12_9_2007</file>
  24   </files>

Using Regular Expressions to validate a fixed length numerical string.

Using Ruby and Regular Sxpressions, this code successfully validates a string if it contains exactly 3 numbers.

   1  
   2  a = '547'
   3  /^\d\d\d$/ ~= a

Using Regular Expressions to validate a numerical string.

Using Ruby and Regular Expressions, this code validates a string for numbers only. If the string variable contains only numbers then 0 will be returned otherwise nil.

   1  
   2  a = '134323'
   3  /^[0-9]*$/ =~ a
   4  #result returns 0, indicating success

Rails URL Validation

No regexes, allows URLs with ports or IPs. Inspiration from here

   1  
   2    validates_each :href, :on => :create do |record, attr, value|
   3      begin
   4        uri = URI.parse(value)
   5        if uri.class != URI::HTTP
   6          record.errors.add(attr, 'Only HTTP protocol addresses can be used')
   7        end
   8      rescue URI::InvalidURIError
   9        record.errors.add(attr, 'The format of the url is not valid.')
  10      end
  11    end

Snazzy url fixer using Ruby's super method

Within the body of a method, a call to super acts just like a call to that original method, except that the search for a method body starts in the superclass of the object that was found to contain the original method.

   1  
   2    def url=(addr)
   3      super (addr.blank? || addr.starts_with?('http')) ? addr : "http://#{addr}"
   4    end


Validate uniqueness of an id pair

   1  
   2  # Prevent user from joining group twice
   3  def validate
   4  	errors.add_to_base("You are already a member of the #{self.group.name} Group") unless Grouping.find(:all, :conditions => {:user_id => self.user_id, :group_id => self.group_id}).blank?
   5  end

Javascript numeric validation

I've seen a lot of takes on numeric validation, and most have serious flaws. For example, (!isNaN) returns inconsistent results and shouldn't be used to verify numericality. This should cover all cases, and supports a decimal point as well as negative numbers.

   1  
   2  function isNumeric(value) {
   3    if (value == null || !value.toString().match(/^[-]?\d*\.?\d*$/)) return false;
   4    return true;
   5  }


This logic is straight-forward: if the parameter isn't null, convert it to a string and match it against a RegEx to throw out false cases. Otherwise, return true.
« Newer Snippets
Older Snippets »
Showing 1-10 of 15 total  RSS