Friday, August 24, 2012

URL validation using regular expression for javascript, Salesforce Apex, Java , PHP & Ruby



Pattern for javascript, Java , PHP & Ruby

/^((http|https):\/\/)?(www[.])?([a-zA-Z0-9]|-)+([.][a-zA-Z0-9(-|\/|=|?)?]+)+$/


Validation function in Javascript

function checkForValidURL(value) {

    var urlregex = new RegExp("^((http|https):\/\/)?(www[.])?([a-zA-Z0-9]|-)+([.][a-zA-Z0-9(-|\/|=|?)?]+)+$");
    if (urlregex.test(value)) {
        return (true);
    }
    return (false);
}

Pattern for Salesforce Apex

  ^((http|https)://)??(www[.])??([a-zA-Z0-9]|-)+?([.][a-zA-Z0-9(-|/|=|?)??]+?)+?$
It can also be used for validation fields and Visualforce pages

Validation function in Apex

public Boolean checkForValidURL(String url){ 
 if(url != Null)   {
    String regexFormat ='(^((http|https)://)??(www[.])??([a-zA-Z0-9]|-)+?([.][a-zA-Z0-9(-|/|=|?)??]+?)+?$)'; 
   Pattern urlFormat = Pattern.Compile(regexFormat); 
   Matcher format_of_url = urlFormat.Match(url);
   if (format_of_url.Matches()){
       return true;       //return true - if success 
   }
 return false ;
}

No comments:

Post a Comment