Archive for the ‘Regular Expressions’ Category

simple JavaScript allow only digits/numbers in input field

Wednesday, October 23rd, 2013

<input onkeypress=”validate(event)” />

function validate(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /[0-9]/;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}

jQuery Regex Selector examples ^=Starts with, $=Ends with, is of Class [0-9] threw in an encodeURIComponent for kicks

Monday, August 12th, 2013

Obviously, if your jQuery version is up to date, you should use .on
but I was fixing one of our sites that is stuck in 1.5,
so here are some examples using .delegate and .bind
The regex blocks are the same either way:

$.fn.popSubject = function() {
var menuA = $(“#askMenuA option:selected”).text();
var menuB = $(“#askMenuB option:selected”).text();
$(‘input[id$=”hiddensubject”]‘).val(menuA + ” – ” + menuB);
}

$(‘[id^=rn_FormSubmit_][id$=_Button]‘).bind(‘click’, ‘button’, function(event){
//Call Omniture when SA initial form submitted
s_exp_trackClick( this, ‘a’,”support.faq.sa.first.” + encodeURIComponent($(“#askMenuA option:selected”).text()) );
});

$(“body”).delegate(‘[id^=rnDialog1_Button][id$=[0-9]]‘, ‘click’, function(event){
//Call Omniture when SA dialog box submitted
s_exp_trackClick( this, ‘a’,’support.faq.sa.pop.’+ encodeURIComponent($(“#askMenuB option:selected”).text()) );
});

Perl valid email regular expression

Tuesday, February 1st, 2011

# Check for valid email address

/
^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*$
/

Php simple phone format

Monday, March 8th, 2010

$phone = 3334449999;
$phone = preg_replace(“/([0-9a-zA-Z]{3})([0-9a-zA-Z]{3})([0-9a-zA-Z]{4})/”, “($1) $2-$3”, $phone);

Regex Expression Password Validation; 1 Uppercase; 1 Lowercase; 1 Number; length of 6 – 20

Tuesday, March 2nd, 2010

function valPassword($Password){

$pRegex = ‘/(?-i)(?m)^(?=.*?\d)(?=.*?[a-z])(?=.*?[A-Z])[a-zA-Z].{6,20}$/’;

if ( preg_match($pRegex, $Password)) { return TRUE; }
return FALSE;

}

Or this also works nicely:

function valPassword($Password)

{

if(
ctype_alnum($Password) // numbers & digits only
&& strlen($Password)>6 // at least 7 chars
//&& strlen($password)<21 // at most 20 chars
&& preg_match(‘`[A-Z]`’,$Password) // at least one upper case
&& preg_match(‘`[a-z]`’,$Password) // at least one lower case
&& preg_match(‘`[0-9]`’,$Password) // at least one digit

)

{

return TRUE;

}
return FALSE;

}

Resource:

http://regexlib.com/REDetails.aspx?regexp_id=31