function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Alex Wong 4Alex Wong 4 

How to perform URL check at apex code level?

My page is a form for user to input data. There are 4 fields for them to input URL, but not necessary. Therefore, validation rule at field level is not suitable for my case. And I want to search for a method to validate URL at apex code level. 
Here is my code, and my 4 URL field are called Website__c, Facebook__c, SoundCloud__c and YouTube__c in custom object "artist".
public class extattachfile {

Public attachment objAttachment{get;set;}
Public attachment objAttachment2{get; set;}
Public attachment objAttachment3{get; set;}
Public attachment objAttachmentt{get; set;}
Public attachment objAttachments{get; set;}
Public Artist__c artist{get; set;}

Public extattachfile(apexpages.standardcontroller stdCon) {
 
objAttachment = new Attachment();
objAttachment2 = new Attachment();
objAttachment3 = new Attachment();
objAttachmentt = new Attachment();
objAttachments = new Attachment();
artist= new Artist__c ();
    }

public PageReference save() {
        Boolean checkAttachment = false;                   
if(artist.Id == null){
            insert artist;
        }


        List<Attachment> attachmentList = new List<Attachment>();
        if(objAttachment.Body != null){
            objAttachment.ParentId = artist.id;
            attachmentList.add(objAttachment);
            checkAttachment = true;
        }
        if(objAttachment2.Body != null){
            objAttachment2.ParentId = artist.id;
            attachmentList.add(objAttachment2);
            checkAttachment = true;
        }
        if(objAttachment3.Body != null){
            objAttachment3.ParentId = artist.id;
            attachmentList.add(objAttachment3);
            checkAttachment = true;
        }
          
List<Attachment> attachmentListother = new List<Attachment>();
        if(objAttachmentt.Body != null){
            objAttachmentt.ParentId = artist.id;
            attachmentList.add(objAttachmentt);
        }
        if(objAttachments.Body != null){
            objAttachments.ParentId = artist.id;
            attachmentList.add(objAttachments);
        }
Insert attachmentListother;
        if(attachmentList.size() > 0 && checkAttachment){
            insert attachmentList;

            // if successfully inserted new contact, then displays the thank you page.
            return Page.ack;
        }else{
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR, 'Please attach at least one photo attachment.'));
            return null;
        }              
      }

 

}

Thank you.
Best Answer chosen by Alex Wong 4
VineetKumarVineetKumar
public class extattachfile {

	Public attachment objAttachment{get;set;}
	Public attachment objAttachment2{get; set;}
	Public attachment objAttachment3{get; set;}
	Public attachment objAttachmentt{get; set;}
	Public attachment objAttachments{get; set;}
	Public Artist__c artist{get; set;}

	Public extattachfile(apexpages.standardcontroller stdCon) {
	 
		objAttachment = new Attachment();
		objAttachment2 = new Attachment();
		objAttachment3 = new Attachment();
		objAttachmentt = new Attachment();
		objAttachments = new Attachment();
		artist= new Artist__c ();
	}

	public PageReference save() {
		Boolean checkAttachment = false;
		Boolean isValidUrl = true;
		if(artist.Id == null){
			if(artist.Website__c != null){
				Pattern emailPattern = Pattern.compile('^((http|https)://)??(www[.])??([a-zA-Z0-9]|-)+?([.][a-zA-Z0-9(-|/|=|?)??]+?)+?$');
				Boolean isMatch = emailPattern.matcher(artist.Website__c).matches();
				if(!isMatch){
					ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR, 'Please provide a valid Website.'));
					isValidUrl = false;
				}
			}
			if(artist.Facebook__c != null){
				Pattern emailPattern = Pattern.compile('^((http|https)://)??(www[.])??([a-zA-Z0-9]|-)+?([.][a-zA-Z0-9(-|/|=|?)??]+?)+?$');
				Boolean isMatch = emailPattern.matcher(artist.Facebook__c).matches();
				if(!isMatch){
					ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR, 'Please provide a valid Facebook URL.'));
					isValidUrl = false;
				}
			}
			if(artist.SoundCloud__c != null){
				Pattern emailPattern = Pattern.compile('^((http|https)://)??(www[.])??([a-zA-Z0-9]|-)+?([.][a-zA-Z0-9(-|/|=|?)??]+?)+?$');
				Boolean isMatch = emailPattern.matcher(artist.SoundCloud__c).matches();
				if(!isMatch){
					ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR, 'Please provide a valid Soundcloud URL.'));
					isValidUrl = false;
				}
			}
			if(artist.YouTube__c != null){
				Pattern emailPattern = Pattern.compile('^((http|https)://)??(www[.])??([a-zA-Z0-9]|-)+?([.][a-zA-Z0-9(-|/|=|?)??]+?)+?$');
				Boolean isMatch = emailPattern.matcher(artist.YouTube__c).matches();
				if(!isMatch){
					ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR, 'Please provide a valid Youtube URL.'));
					isValidUrl = false;
				}
			}
			if(isValidUrl){
				insert artist;
			}else{
				return null;
			}
		}


		List<Attachment> attachmentList = new List<Attachment>();
		if(objAttachment.Body != null){
			objAttachment.ParentId = artist.id;
			attachmentList.add(objAttachment);
			checkAttachment = true;
		}
		if(objAttachment2.Body != null){
			objAttachment2.ParentId = artist.id;
			attachmentList.add(objAttachment2);
			checkAttachment = true;
		}
		if(objAttachment3.Body != null){
			objAttachment3.ParentId = artist.id;
			attachmentList.add(objAttachment3);
			checkAttachment = true;
		}
		  
		List<Attachment> attachmentListother = new List<Attachment>();
		if(objAttachmentt.Body != null){
			objAttachmentt.ParentId = artist.id;
			attachmentList.add(objAttachmentt);
		}
		if(objAttachments.Body != null){
			objAttachments.ParentId = artist.id;
			attachmentList.add(objAttachments);
		}
		Insert attachmentListother;
		if(attachmentList.size() > 0 && checkAttachment){
			insert attachmentList;

			// if successfully inserted new contact, then displays the thank you page.
			return Page.ack;
		}else{
			ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR, 'Please attach at least one photo attachment.'));
			return null;
		}              
	}
}

Tweak it as per your requirement.

Do mark it as a best answer if it helped solve your problem.

All Answers

VineetKumarVineetKumar
Try this :
Pattern emailPattern = Pattern.compile('^((http|https)://)??(www[.])??([a-zA-Z0-9]|-)+?([.][a-zA-Z0-9(-|/|=|?)??]+?)+?$');
Boolean isMatch = emailPattern.matcher(artist.Website__c).matches();
system.debug('#### isMatch = '+isMatch);
Alex Wong 4Alex Wong 4
It do not have any effect, even I type a wrong format for URL. Like I input 123 for the field.
VineetKumarVineetKumar
When you inputted the value, did you check what is the output of isMatch?
This will return true/false for a valid/invalid URL, and it's working for me..
Alex Wong 4Alex Wong 4
It turns out in error:
System.NullPointerException: Script-thrown exception
Error is in expression '{!save}' in component <apex:commandButton> in page form: Class.System.Pattern.matcher: line 30, column 1
Class.extattachfile.save: line 38, column 1


Here is my code:
public class extattachfile {

Public attachment objAttachment{get;set;}
Public attachment objAttachment2{get; set;}
Public attachment objAttachment3{get; set;}
Public attachment objAttachmentt{get; set;}
Public attachment objAttachments{get; set;}
Public Artist__c artist{get; set;}

Public extattachfile(apexpages.standardcontroller stdCon) {
 
objAttachment = new Attachment();
objAttachment2 = new Attachment();
objAttachment3 = new Attachment();
objAttachmentt = new Attachment();
objAttachments = new Attachment();
artist= new Artist__c ();
    }

public PageReference save() {
        Boolean checkAttachment = false;


if(artist.Id == null){
Pattern emailPattern = Pattern.compile('^((http|https)://)??(www[.])??([a-zA-Z0-9]|-)+?([.][a-zA-Z0-9(-|/|=|?)??]+?)+?$');
Boolean isMatch = emailPattern.matcher(artist.Facebook__c).matches();
system.debug('#### isMatch = '+isMatch);

            insert artist;
        }


        List<Attachment> attachmentList = new List<Attachment>();
        if(objAttachment.Body != null){
            objAttachment.ParentId = artist.id;
            attachmentList.add(objAttachment);
            checkAttachment = true;
        }
        if(objAttachment2.Body != null){
            objAttachment2.ParentId = artist.id;
            attachmentList.add(objAttachment2);
            checkAttachment = true;
        }
        if(objAttachment3.Body != null){
            objAttachment3.ParentId = artist.id;
            attachmentList.add(objAttachment3);
            checkAttachment = true;
        }
          
List<Attachment> attachmentListother = new List<Attachment>();
        if(objAttachmentt.Body != null){
            objAttachmentt.ParentId = artist.id;
            attachmentList.add(objAttachmentt);
        }
        if(objAttachments.Body != null){
            objAttachments.ParentId = artist.id;
            attachmentList.add(objAttachments);
        }
Insert attachmentListother;
        if(attachmentList.size() > 0 && checkAttachment){
            insert attachmentList;

            // if successfully inserted new contact, then displays the thank you page.
            return Page.ack;
        }else{
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR, 'Please attach at least one photo attachment.'));
            return null;
        }              
      }

 

}

 
Alex Wong 4Alex Wong 4
line 38 is line 26 here
Alex Wong 4Alex Wong 4
This time, it just pass even if I input a wrong format (not include http).
VineetKumarVineetKumar
That should be ok I guess, cos http/https is not a mandatory specification for URL
www.google.com will automatically get typecasted with the applicable protocol.

This should fail for abc / 123 inputted in the URL field, but will pass for www.google.com.
Alex Wong 4Alex Wong 4
It passes even when I type 123 for the url field...
VineetKumarVineetKumar
Check this, probably I missed a not condition
public class extattachfile {

	Public attachment objAttachment{get;set;}
	Public attachment objAttachment2{get; set;}
	Public attachment objAttachment3{get; set;}
	Public attachment objAttachmentt{get; set;}
	Public attachment objAttachments{get; set;}
	Public Artist__c artist{get; set;}

	Public extattachfile(apexpages.standardcontroller stdCon) {
	 
		objAttachment = new Attachment();
		objAttachment2 = new Attachment();
		objAttachment3 = new Attachment();
		objAttachmentt = new Attachment();
		objAttachments = new Attachment();
		artist= new Artist__c ();
	}

	public PageReference save() {
		Boolean checkAttachment = false;
		if(artist.Id == null){
			if(artist.Facebook__c != null){
				Pattern emailPattern = Pattern.compile('^((http|https)://)??(www[.])??([a-zA-Z0-9]|-)+?([.][a-zA-Z0-9(-|/|=|?)??]+?)+?$');
				Boolean isMatch = emailPattern.matcher(artist.Facebook__c).matches();
				system.debug('#### isMatch = '+isMatch);
				if(!isMatch){
					ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR, 'Please provide a valid Facebook URL.'));
					return null;
				}
			}
			insert artist;
		}


		List<Attachment> attachmentList = new List<Attachment>();
		if(objAttachment.Body != null){
			objAttachment.ParentId = artist.id;
			attachmentList.add(objAttachment);
			checkAttachment = true;
		}
		if(objAttachment2.Body != null){
			objAttachment2.ParentId = artist.id;
			attachmentList.add(objAttachment2);
			checkAttachment = true;
		}
		if(objAttachment3.Body != null){
			objAttachment3.ParentId = artist.id;
			attachmentList.add(objAttachment3);
			checkAttachment = true;
		}
		  
		List<Attachment> attachmentListother = new List<Attachment>();
		if(objAttachmentt.Body != null){
			objAttachmentt.ParentId = artist.id;
			attachmentList.add(objAttachmentt);
		}
		if(objAttachments.Body != null){
			objAttachments.ParentId = artist.id;
			attachmentList.add(objAttachments);
		}
		Insert attachmentListother;
		if(attachmentList.size() > 0 && checkAttachment){
			insert attachmentList;

			// if successfully inserted new contact, then displays the thank you page.
			return Page.ack;
		}else{
			ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR, 'Please attach at least one photo attachment.'));
			return null;
		}              
	}
}
Alex Wong 4Alex Wong 4
It works finally, thank you so much!!! But how to make it to a 4-time URL check?
VineetKumarVineetKumar
What are the 4 URL's that you want to check?
Alex Wong 4Alex Wong 4
Website__c, Facebook__c, SoundCloud__c, YouTube__c
Thank you very much, coz I am vreally new for apex.
VineetKumarVineetKumar
public class extattachfile {

	Public attachment objAttachment{get;set;}
	Public attachment objAttachment2{get; set;}
	Public attachment objAttachment3{get; set;}
	Public attachment objAttachmentt{get; set;}
	Public attachment objAttachments{get; set;}
	Public Artist__c artist{get; set;}

	Public extattachfile(apexpages.standardcontroller stdCon) {
	 
		objAttachment = new Attachment();
		objAttachment2 = new Attachment();
		objAttachment3 = new Attachment();
		objAttachmentt = new Attachment();
		objAttachments = new Attachment();
		artist= new Artist__c ();
	}

	public PageReference save() {
		Boolean checkAttachment = false;
		Boolean isValidUrl = true;
		if(artist.Id == null){
			if(artist.Website__c != null){
				Pattern emailPattern = Pattern.compile('^((http|https)://)??(www[.])??([a-zA-Z0-9]|-)+?([.][a-zA-Z0-9(-|/|=|?)??]+?)+?$');
				Boolean isMatch = emailPattern.matcher(artist.Website__c).matches();
				if(!isMatch){
					ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR, 'Please provide a valid Website.'));
					isValidUrl = false;
				}
			}
			if(artist.Facebook__c != null){
				Pattern emailPattern = Pattern.compile('^((http|https)://)??(www[.])??([a-zA-Z0-9]|-)+?([.][a-zA-Z0-9(-|/|=|?)??]+?)+?$');
				Boolean isMatch = emailPattern.matcher(artist.Facebook__c).matches();
				if(!isMatch){
					ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR, 'Please provide a valid Facebook URL.'));
					isValidUrl = false;
				}
			}
			if(artist.SoundCloud__c != null){
				Pattern emailPattern = Pattern.compile('^((http|https)://)??(www[.])??([a-zA-Z0-9]|-)+?([.][a-zA-Z0-9(-|/|=|?)??]+?)+?$');
				Boolean isMatch = emailPattern.matcher(artist.SoundCloud__c).matches();
				if(!isMatch){
					ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR, 'Please provide a valid Soundcloud URL.'));
					isValidUrl = false;
				}
			}
			if(artist.YouTube__c != null){
				Pattern emailPattern = Pattern.compile('^((http|https)://)??(www[.])??([a-zA-Z0-9]|-)+?([.][a-zA-Z0-9(-|/|=|?)??]+?)+?$');
				Boolean isMatch = emailPattern.matcher(artist.YouTube__c).matches();
				if(!isMatch){
					ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR, 'Please provide a valid Youtube URL.'));
					isValidUrl = false;
				}
			}
			if(isValidUrl){
				insert artist;
			}else{
				return null;
			}
		}


		List<Attachment> attachmentList = new List<Attachment>();
		if(objAttachment.Body != null){
			objAttachment.ParentId = artist.id;
			attachmentList.add(objAttachment);
			checkAttachment = true;
		}
		if(objAttachment2.Body != null){
			objAttachment2.ParentId = artist.id;
			attachmentList.add(objAttachment2);
			checkAttachment = true;
		}
		if(objAttachment3.Body != null){
			objAttachment3.ParentId = artist.id;
			attachmentList.add(objAttachment3);
			checkAttachment = true;
		}
		  
		List<Attachment> attachmentListother = new List<Attachment>();
		if(objAttachmentt.Body != null){
			objAttachmentt.ParentId = artist.id;
			attachmentList.add(objAttachmentt);
		}
		if(objAttachments.Body != null){
			objAttachments.ParentId = artist.id;
			attachmentList.add(objAttachments);
		}
		Insert attachmentListother;
		if(attachmentList.size() > 0 && checkAttachment){
			insert attachmentList;

			// if successfully inserted new contact, then displays the thank you page.
			return Page.ack;
		}else{
			ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR, 'Please attach at least one photo attachment.'));
			return null;
		}              
	}
}

Tweak it as per your requirement.

Do mark it as a best answer if it helped solve your problem.
This was selected as the best answer
Alex Wong 4Alex Wong 4
The problem is sloved!!! Thanks for your big help!!!
One more thing to ask. How to solve the view state size problem. When I test the page with small-sized attachment, it passes. But when I test the page with 5 5-mb attachment, the actual view state size is obviously too large (22,823KB) which is over the maximum view state size limit (135KB). Is there any solution to make the page view state size itself lower, to make there are more view state for attachment processing. 
Alex Wong 4Alex Wong 4
The view state size problem occur only when the all 4 URL are in wrong format. I guess maybe the apex is too costly for the view state size. If there are not wrong formatted URL, even I input 5 5-mb attachment, it is still ok.
VineetKumarVineetKumar
After doing the Insert DML, clear out all the attachment objects.
Just do : 
objAttachment.Body = null;
objAttachment2.Body = null
objAttachment3.Body = null
objAttachmentt.Body = null
objAttachments.Body = null

and also : 
attachmentListother.clear();
attachmentList.clear();
VineetKumarVineetKumar
You need to clear out, all the attachment object in case of error as well, and as the user to again re attach the file.
 
Alex Wong 4Alex Wong 4
public class extattachfile {
    Public attachment objAttachment{get;set;}
    Public attachment objAttachment2{get; set;}
    Public attachment objAttachment3{get; set;}
    Public attachment objAttachmentt{get; set;}
    Public attachment objAttachments{get; set;}
    Public Artist__c artist{get; set;}
    Public extattachfile(apexpages.standardcontroller stdCon) {
        objAttachment = new Attachment();
        objAttachment2 = new Attachment();
        objAttachment3 = new Attachment();
        objAttachmentt = new Attachment();
        objAttachments = new Attachment();
        artist= new Artist__c ();
    }
    public PageReference save() {
        Boolean checkAttachment = false;
        Boolean isValidUrl = true;
        if(artist.Id == null){
            if(artist.Website__c != null){
                Pattern emailPattern = Pattern.compile('^((http|https)://)??(www[.])??([a-zA-Z0-9]|-)+?([.][a-zA-Z0-9(-|/|=|?)??]+?)+?$');
                Boolean isMatch = emailPattern.matcher(artist.Website__c).matches();
                if(!isMatch){
                    objAttachment.Body = null;
objAttachment2.Body = null;
objAttachment3.Body = null;
objAttachmentt.Body = null;
objAttachments.Body = null;
                    ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR, 'Please provide a valid Website URL.'));
                    isValidUrl = false;
                }
            }
            if(artist.Facebook__c != null){
                Pattern emailPattern = Pattern.compile('^((http|https)://)??(www[.])??([a-zA-Z0-9]|-)+?([.][a-zA-Z0-9(-|/|=|?)??]+?)+?$');
                Boolean isMatch = emailPattern.matcher(artist.Facebook__c).matches();
                if(!isMatch){
                    objAttachment.Body = null;
objAttachment2.Body = null;
objAttachment3.Body = null;
objAttachmentt.Body = null;
objAttachments.Body = null;
                    ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR, 'Please provide a valid Facebook URL.'));
                    isValidUrl = false;
                }
            }
            if(artist.SoundCloud__c != null){
                Pattern emailPattern = Pattern.compile('^((http|https)://)??(www[.])??([a-zA-Z0-9]|-)+?([.][a-zA-Z0-9(-|/|=|?)??]+?)+?$');
                Boolean isMatch = emailPattern.matcher(artist.SoundCloud__c).matches();
                if(!isMatch){
                    objAttachment.Body = null;
objAttachment2.Body = null;
objAttachment3.Body = null;
objAttachmentt.Body = null;
objAttachments.Body = null;
                    ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR, 'Please provide a valid Soundcloud URL.'));
                    isValidUrl = false;
                }
            }
            if(artist.YouTube__c != null){
                Pattern emailPattern = Pattern.compile('^((http|https)://)??(www[.])??([a-zA-Z0-9]|-)+?([.][a-zA-Z0-9(-|/|=|?)??]+?)+?$');
                Boolean isMatch = emailPattern.matcher(artist.YouTube__c).matches();
                if(!isMatch){
                    objAttachment.Body = null;
objAttachment2.Body = null;
objAttachment3.Body = null;
objAttachmentt.Body = null;
objAttachments.Body = null;
                    ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR, 'Please provide a valid Youtube URL.'));
                    isValidUrl = false;
                }
            }
            if(isValidUrl){
                insert artist;
            }else{
                return null;
            }
        }
        List<Attachment> attachmentList = new List<Attachment>();
        if(objAttachment.Body != null){
            objAttachment.ParentId = artist.id;
            attachmentList.add(objAttachment);
            checkAttachment = true;
        }
        if(objAttachment2.Body != null){
            objAttachment2.ParentId = artist.id;
            attachmentList.add(objAttachment2);
            checkAttachment = true;
        }
        if(objAttachment3.Body != null){
            objAttachment3.ParentId = artist.id;
            attachmentList.add(objAttachment3);
            checkAttachment = true;
        }          
        List<Attachment> attachmentListother = new List<Attachment>();
        if(objAttachmentt.Body != null){
            objAttachmentt.ParentId = artist.id;
            attachmentList.add(objAttachmentt);
        }
        if(objAttachments.Body != null){
            objAttachments.ParentId = artist.id;
            attachmentList.add(objAttachments);
        }
        Insert attachmentListother;
        if(attachmentList.size() > 0 && checkAttachment){
            insert attachmentList;
            attachmentList = null;
            // if successfully inserted new contact, then displays the thank you page.
            return Page.ack;
        }else{
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR, 'Please attach at least one photo attachment.'));
            return null;
        }             
    }
}

It seems working fine after you suggestion. Is there any improvement for the above code? Thank you.
VineetKumarVineetKumar
Perhaps you may want to follow a more modular approach to you classes and reduce the number of lines and complexity of your code.
Also, you can refer various design patterns to learn more on Apex
Alex Wong 4Alex Wong 4
Really appreciate for your help!!!