Tag Archive for validation

Assure a valid email that .Net can actually send an email to is passed.

protected void ValidEmail(object source, ServerValidateEventArgs args)
		{
			try
			{
				var a = new MailAddress(args.Value);
			}
			catch (Exception ex)
			{
				args.IsValid = false;
				return;
			}
			args.IsValid = true;
		}

source

Validate IBAN number with PHP

// functioan
function IbanValidation($value) {
    $iban = false;
    $value= strtoupper(trim($value));
 
// Country US (can be changed into your country)
if(preg_match('/^USd{7}0[A-Z0-9]{16}$/', $value)) {
        $number = substr($value,4,22).'2927'.substr($value,2,2);
        $number = str_replace(
 
// Arrays in arrays
array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'),
 
array(10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35),
            $number
        );
 
        $iban = (1 == bcmod($number,97)) ? true:false;
    }
// return
return $iban;
}

source

KickApps – Change form validation to use JQuery. Fixes issues with IE

if(Ka.Info.PAGE == "login/registerUser.jsp"){
    if (Ka && Ka.formValidation) {        
        Ka.formValidation.rules['password-match-with'].test = function(val,propVal){return (val == $j('#' + propVal).val()); }
    }
}

source

Very Simple Form Validation (skeleton)

document.getElementsByAttribute = function( attrib, value, context_node, tag ) {
    var nodes = [];
    if ( context_node == null )
        context_node = this;
    if ( tag == null ) 
        tag = '*';
    var elems = context_node.getElementsByTagName(tag);

    for ( var i = 0; i < elems.length; i += 1 ) {
        if ( value ) {
            if ( elems[i].hasAttribute(attrib) && elems[i].getAttribute(attrib) == value )
                nodes.push(elems[i]);
        } else {
            if ( elems[i].hasAttribute(attrib) )
                nodes.push(elems[i]);
        }
    }
    return nodes;
}

if (typeof validateElementsByRule != "function") {
    var validateElementsByRule = function( form_node, options, patterns ) {

        if ( !options ) {
            options = {
                livetype: false,
                errorBlock: true,
                errorBefore: "<li>",
                errorAfter: "</li>"
            };
        }

        if ( !patterns ) {
            patterns = {
                "required": {
                    filter: /^S+$/,
                    error: "Required!"
                },
                "digits": {
                    filter: /^d+$/,
                    error: "Please enter digits only."
                },
                "zip": {
                    filter: /(^d{5}$)|(^d{5}-d{4}$)/,
                    error: "Please provide a valid zip or postal code."
                }
            };
        }

        var errors = [];

        var elems = document.getElementsByAttribute( "data-validation", "", form_node );
        for ( var i = 0; i < elems.length; i += 1 ) {
            var reg = new RegExp(patterns[elems[i].getAttribute("data-validation")].filter);
            if ( !reg.test(elems[i].value) ) {
                // store @id and error message
                errors.push([
                    elems[i].getAttribute("id"),
                    patterns[elems[i].getAttribute("data-validation")].error
                ]);
            }
        }

        if (options.livetype) {
            for ( var p = 0; p < errors.length; p += 1 ) {
                document.getElementById(errors[p][0]).onkeyup = function() {
                    validateElementsByRule( form_node, options, patterns);
                }
            }
        }

        if (options.errorBlock) {
            
            var errorBlockChild = document.getElementById("error-block");
            if (errorBlockChild) {
                var errorBlockParent = errorBlockChild.parentNode;
                errorBlockParent.removeChild(errorBlockChild);
            }
            
            var error_output = "<ol>";
            for ( var p = 0; p < errors.length; p += 1 ) {
                error_output += options.errorBefore+"<label for="+errors[p][0]+">"+errors[p][1]+"</label>"+options.errorAfter;
            }
            error_output += "</ol>";
            var errorBlock = document.createElement("div");
            errorBlock.setAttribute("id", "error-block");
            errorBlock.innerHTML = error_output;
            var parentDiv = form_node.parentNode;
            parentDiv.insertBefore(errorBlock, form_node);
        }

        return errors;

    }
}

window.onload = function() {
    var new_form = document.getElementById('theform');
    var options = {
        livetype: true,
        errorBlock: true,
        errorBefore: "<li>",
        errorAfter: "</li>"
    }
    new_form.onsubmit = function() {
        if ( validateElementsByRule( new_form, options).length ) {
            console.log( validateElementsByRule( new_form, options) );
            return false;
        }
    }
};

/*
Test inputs:
<form id="theform" action="" method="post">
    <input id="cheese" value="" type="text" data-validation="required" />
    <input id="cheese2" value="" type="text" data-validation="zip" />
    <input type="submit" value="Validate" />
</form>
*/

source

Extender validacion de Codeigniter

//Create: "application/libraries/MY_Form_validation.php"
class MY_Form_validation extends CI_Form_validation {

	function unique($value, $params) {

		$CI =& get_instance();
		$CI->load->database();

		$CI->form_validation->set_message('unique',
			'The %s is already being used.');

		list($table, $field) = explode(".", $params, 2);

		$query = $CI->db->select($field)->from($table)
			->where($field, $value)->limit(1)->get();

		if ($query->row()) {
			return false;
		} else {
			return true;
		}

	}
}

source

Poor Man’s jQuery Validation (or jQuery Proof)

Array.prototype.unique = function () {
	var r = new Array();
	o:for(var i = 0, n = this.length; i < n; i++)
	{
		for(var x = 0, y = r.length; x < y; x++)
		{
			if(r[x]==this[i])
			{
				continue o;
			}
		}
		r[r.length] = this[i];
	}
	return r;
}

$proof = {
	
	errorStoreTest: [],
	
	options: {
		livetype: false
	},
	
	pattern: {
		"required": {
			filter: /^S+$/,
			msg: "Please fill in this field."
		},
		"e-mail": {
			filter: /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/,
			msg: "Please provide a valid e-mail address."
		},
		"digits": {
			filter: /^d+$/,
			msg: "Please enter digits only."
		},
		"zip": {
			filter: /(^d{5}$)|(^d{5}-d{4}$)/,
			msg: "Please provide a valid zip or postal code."
		},
		"min-length": {
			filter: /^.{0,}$/,
			msg: "Min length error."
		},
		"max-length": {
			filter: /^.{0,65535}$/,
			msg: "Max length error."
		}
	},
	
	validator: function(form, options) {
		var validate = this;
		var defaults = this.options;
		
		if(options) {
			//use custom options
		} else {
			//use defaults
		}
		
		form.submit(function(e) {
			var elems = form.find(':input[class*=required], :input[class*=e-mail], :input[class*=number], :input[class*=zip], :input[class*=min-length], :input[class*=max-length]');
			//var elems = form.find(':input[class*=required], :input[class*=number], :input[class*=zip], :input[class*=min-length], :input[class*=max-length]');
			
			//reset error business
			var errorStore = {};
			
			validate.errorStoreTest = [];
			
			$('#error-container').remove();
			var errorOutputHead = "<div id="error-container"><div class="content"><p></p><ul>";
			var errorOutput = "";
			var errorOutputFoot = "</ul></div></div>";
			form.find('input.error, textarea.error, select.error').removeClass('error');
			
			//validate options into array to isolate and test against only them
			var a = [];
			for (name in validate.pattern) {
				a.push(name);
			}
			
			//check for errors
			for (var i = 0; i < elems.length; i += 1) {
				var elem = $(elems[i]);
				var elemClass = elem.attr('class');
				var elemClassSplit = elemClass.split(" ");
				
				
				for (var j = 0; j < elemClassSplit.length; j += 1) {
					//validate options into array to isolate and test against only them
					var newElemPatternType = elemClassSplit[j];
					
					//for min/max (it's ugly, I know -- guh)
					var result = /min-length-d|max-length-d/.exec(elemClassSplit[j]);
					if(result) {
						if (result.toString().indexOf('min') != -1) {
							var min = elemClassSplit[j].toString().split("-")[2];
							var newElemPatternType = newElemPatternType.replace("-"+min, ""); //reshapes to ping pattern name
							var newFilter = validate.pattern[newElemPatternType].filter.toString();
							newFilter = newFilter.replace("0", min);
						} else {
							var max = elemClassSplit[j].toString().split("-")[2];
							var newElemPatternType = newElemPatternType.replace("-"+max, ""); //reshapes to ping pattern name
							var newFilter = validate.pattern[newElemPatternType].filter.toString();
							newFilter = newFilter.replace("65535", max);
						}
					} else {
						if ( $.inArray(newElemPatternType, a) != -1 ) {
							var newFilter = validate.pattern[newElemPatternType].filter.toString();
						}
					}
					
					if ( $.inArray(newElemPatternType, a) != -1 ) {
						
						//parse out the modifier and slashes, since we cannot convert 
						//valid regex [strings] back into regex objects
						newFilter = newFilter.replace("", "").replace("/", "").replace("/", "").replace("i", "").toString();
						var reg = new RegExp(newFilter);
						
						if ( !reg.test(elem.val()) ) {
							//errors! - for inline presentation
							elem.parent().addClass('error');
							elem.addClass('error');
							
							//errors! - for error block
							//errorStore.names.push("#"+elem.attr('id'));
							//errorStore.types.push(validate.pattern[newElemPatternType]);
							//errorStore.messages.push(validate.pattern[newElemPatternType].msg);
							
							var error_name = elem.attr('id').toString();
							
							
							validate.errorStoreTest.push({
								error: { 
									error_id: "#"+error_name,
									error_type: {
										error_type_name: newElemPatternType,
										error_filter: newFilter,
										error_msg: validate.pattern[newElemPatternType].msg 
									}
								}
							});
							
							errorOutput += "<li><label for=""+elem.attr('id')+""><span class="field-name">"+elem.parent().prev().find('label').text()+"</span> <span class="field-error-msg">"+validate.pattern[newElemPatternType].msg+"</span></label></li>";
						}
					}
				}
			}
			
			if(options.livetype) {
				var errStr = validate.errorStoreTest;
				for (var k = 0; k < errStr.length; k += 1) {
					var livereg = new RegExp(errStr[k].error.error_type.error_filter.toString());
					$(errStr[k].error.error_id).queue(function() {
						$(this).change(function() {
							var valStr = $(this).val();
							if ( !livereg.test(valStr) ) {
								$(this).addClass('error');
							} else 
							} else {
								delete errStr[k];
							}
							
							
							//alert( errStr.length );
						});
					});
				}
			}
			
			if(validate.errorStoreTest.length) {
				//display error block
				form.before(errorOutputHead+errorOutput+errorOutputFoot);
				e.preventDefault();
			} else {
				//remove it if the array is empty
				$('#error-container').remove();
			}
			
			//clean up?
			
		});
	}
};

source

User input validation in Visual Studio .NET using MaskedTextBoxes and an ErrorProvider

private void PrimaryForm_Load(object sender, EventArgs e)
{
    maskedTextBox1.ValidatingType = typeof (int);
    maskedTextBox1.TypeValidationCompleted +=
        maskedTextBox1_TypeValidationCompleted;
}

void maskedTextBox1_TypeValidationCompleted(object sender, TypeValidationEventArgs e)
{
    MessageBox.Show("maskedTextBox1_TypeValidationCompleted");
    if (e.IsValidInput)
    {
        var intInput = (int)e.ReturnValue;
        // Do something
        errorProvider.Clear();
    }
    else
    {
        errorProvider.SetError((Control)sender, e.Message);
        //errorProvider.SetError(maskedTextBox1, e.Message);
    }
}

source

Mac Address validation on Zend Validate with regex

$validator = new Zend_Validate_Regex('/([a-fA-F0-9]{2}[:|-]?){6}/');
 $valid = $validator->isValid($mac);

source

HTTP Proxy Checker

#!/bin/bash
# HTTP Proxy Server's IP Address (or URL)
proxy_server=$1

# HTTP Proxy Server's Port Number
port=$2

# We're trying to reach this url via the given HTTP Proxy Server
# (http://www.google.com by default)
url="http://www.google.com"

# Timeout time (in seconds)
timeout=20

# We're fetching the return code and assigning it to the $result variable
result=`HEAD -d -p <a href="http://$proxy_server:$port" >http://$proxy_server:$port</a> -t $timeout $url`

# If the return code is 200, we've reached to $url successfully
if [ "$result" = "200 OK" ]; then
echo "1 (proxy works)"
# Otherwise, we've got a problem (either the HTTP Proxy Server does not work
# or the request timed out)
else
echo "0 (proxy does not work or request timed out)"
fi

source

Check if username is in use

Function CheckExistingUsername(ByVal username As String) As Boolean

Dim UserExists As Boolean = False
Dim strConn As String = System.Configuration.ConfigurationManager.ConnectionStrings("Fullconnection").ConnectionString
Dim MySQL As String = "Select username from tUser where Username=@Username"
Dim MyConn As New SqlConnection(strConn)
Dim objDR As SqlDataReader
Dim Cmd As New SqlCommand(MySQL, MyConn)
Cmd.Parameters.Add(New SqlParameter("@Username", username))

Try
MyConn.Open()
objDR = Cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection)

While objDR.Read()
UserExists = True
End While

Catch ex As Exception
LogError("GlobalClass.vb :: CheckExistingUsername", ex.ToString)
Finally
MyConn.Close()
CheckExistingUsername = UserExists
End Try
End Function

source