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 

URL validation through apex

Since the field type URL cannot check for the data whether it is really a URL or not, I want to ask for how to write a controller for check the URL when submiting. Thank you for all your work!
Best Answer chosen by Alex Wong 4
VineetKumarVineetKumar
Ok, and the final solution to your problem was :
  • First create a validation with the below formulas:
  1. IF(REGEX(URLfield__c,"^((http|https)://)??(www[.])??([a-zA-Z0-9]|-)+?([.][a-zA-Z0-9(-|/|=|?)??]+?)+?$"),false,true)
    This validation will prevent any wrong insertion of website.
  • Second to put a condition check in the controller class to display custom message.
  • try{
    	if(artist.Id == null){
    		insert artist;
    	}
    }catch (DMLException e) {
    	if(e.getMessage().contains('FIELD_CUSTOM_VALIDATION_EXCEPTION') && e.getMessage().contains('Facebook__c')){
    		ApexPages.addMessage(newApexPages.message(ApexPages.severity.ERROR,'Facebook: Please enter a valid URL.'));
    	}else{
    		ApexPages.addMessage(newApexPages.message(ApexPages.severity.ERROR,string.valueof(e)));
    	}
    	return null;
    }

All Answers

VineetKumarVineetKumar
For Apex you will have to either go with Javascript / Jquery to do a REGEX check for validating the URL
As an alternative, Since you already have the data in the URL field, create a validation rule for checking then REGEX on it.
REGEX code can be found below :
if(REGEX(URLfield__c,"^((http|https)://)??(www[.])??([a-zA-Z0-9]|-)+?([.][a-zA-Z0-9(-|/|=|?)??]+?)+?$"),false,true)
Alex Wong 4Alex Wong 4
It turns out to have a error... Error: extattachfile Compile Error: line 22:36 no viable alternative at character '"' at line 22 column 36
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(REGEX(artist.Facebook__c,"^((http|https)://)??(www[.])??([a-zA-Z0-9]|-)+?([.][a-zA-Z0-9(-|/|=|?)??]+?)+?$"),false,true)
                    {if(artist.Id == null)
                    {insert artist;}}
        else {ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR, 'Please insert correct URL.'));
            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;
        }              
      }

 

}

Thank you so much!
VineetKumarVineetKumar
REGEX is a formaula option, you cannot use it directly here in a class.
I asked you to create a formula field (return type checkbox) and then use this REGEX there.
Secondly write a validation rule, checking for this formula, which if false should return you a validation error.
Alex Wong 4Alex Wong 4
When I create a formula checkbox and typed in the if statement, it shows this error:
Error: Function REGEX may not be used in this type of formula

How can I solve it?
VineetKumarVineetKumar
Really my bad..!! Don't know what I was thinking, just over complicating things.. :-\
Just copy paste the above in a validation rule (In formulas REGEX is not supported), not need for a formula.

Do mark my answer as a best answer if it helped.
Alex Wong 4Alex Wong 4
It seems that it cannot show error message through the error message area. It lead to a data crash during inserting. I think I should get a check before insert, that means I need to put that condition in the apex code. But would you do me a favour for the code, please? How to do the same thing on apex code?
VineetKumarVineetKumar
No don't overcomplicate it.
You need to do an exception handling to get the error on the page in a handled way rather than beraking the page something like below:
try{
    insert artist;
}catch(Exception ex){
    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, 'Error : '+ex.getMessage()));
    return null;
}    
It's better to do it in validation rule, cos what if someone from back-end inserts value, at that time you won't be able to catch the wrong url.
Let me know if that still didn't work
 
Alex Wong 4Alex Wong 4
It is really near to my expected outcome. One more things to ask. Now the validation can be done and the error message came out. However, since the field is a custom field, the error message is like this (my field is called Facebook):
Errors
Facebook: Please enter a valid URL.
Error : Insert failed. First exception on row 0; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, Please enter a valid URL.: [Facebook__c]

The first statement is mine and I do not want the second statement come out. How can I solve this problem?
VineetKumarVineetKumar
Can you paste how you are creating your message, the controller lines.
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;
                    try{
                    if(artist.Id == null) 
                    {insert artist;}}
                    catch (DMLException e) {
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,string.valueof(e)));
            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;
        }              
      }

 

}

 
VineetKumarVineetKumar
Check this out : 
try{
	if(artist.Id == null){
		insert artist;
	}
}catch (DMLException e) {
	if(e.getMessage().contains('FIELD_CUSTOM_VALIDATION_EXCEPTION')){
		ApexPages.addMessage(newApexPages.message(ApexPages.severity.ERROR,'Facebook: Please enter a valid URL.'));
	}else{
		ApexPages.addMessage(newApexPages.message(ApexPages.severity.ERROR,string.valueof(e)));
	}
	return null;
}
Try print e.getMessage() and see what happens rather than doing string.valueOf(e) : which will return the whole stack trace.
Alex Wong 4Alex Wong 4
THANKS!!! But what if I get 4 URL links? How to differentiate each of them and show different error message by this method?
VineetKumarVineetKumar
Perhaps you will have to do is to make coditional IF-ELSE inside the catch block, and check for the field name a well
Something like :
try{
	if(artist.Id&nbsp;==&nbsp;null){
		insert&nbsp;artist;
	}
}catch&nbsp;(DMLException e) {
	if(e.getMessage().contains('FIELD_CUSTOM_VALIDATION_EXCEPTION') && e.getMessage().contains('Facebook__c')){
		ApexPages.addMessage(newApexPages.message(ApexPages.severity.ERROR,'Facebook: Please enter a valid URL.'));
	}else{
		ApexPages.addMessage(newApexPages.message(ApexPages.severity.ERROR,string.valueof(e)));
	}
	return&nbsp;null;
}
Do mark my answer as best answer if it helped you!
Alex Wong 4Alex Wong 4
What does "&nbsp" means for?
By the way, can you do a favour for me? When we reach the end of the question, can you gather the information and I would choose that one so that other users can get help from it. Thank you.
VineetKumarVineetKumar
Another common use of the non-breaking space is to prevent that browsers truncate spaces in HTML pages. If you write 10 spaces in your text, the browser will remove 9 of them. To add real spaces to your text, you can use the &nbsp; character entity.
VineetKumarVineetKumar
Ok, and the final solution to your problem was :
  • First create a validation with the below formulas:
  1. IF(REGEX(URLfield__c,"^((http|https)://)??(www[.])??([a-zA-Z0-9]|-)+?([.][a-zA-Z0-9(-|/|=|?)??]+?)+?$"),false,true)
    This validation will prevent any wrong insertion of website.
  • Second to put a condition check in the controller class to display custom message.
  • try{
    	if(artist.Id&nbsp;==&nbsp;null){
    		insert&nbsp;artist;
    	}
    }catch&nbsp;(DMLException e) {
    	if(e.getMessage().contains('FIELD_CUSTOM_VALIDATION_EXCEPTION') && e.getMessage().contains('Facebook__c')){
    		ApexPages.addMessage(newApexPages.message(ApexPages.severity.ERROR,'Facebook: Please enter a valid URL.'));
    	}else{
    		ApexPages.addMessage(newApexPages.message(ApexPages.severity.ERROR,string.valueof(e)));
    	}
    	return&nbsp;null;
    }
This was selected as the best answer
Alex Wong 4Alex Wong 4
One more and thing to go. How to show the different error messgae for different URL field checking? My custom fields are "Facebook", "Website", "YouTube" and "SoundCloud". Thanks.
Alex Wong 4Alex Wong 4
VineetKumar, here comes some problem.
My original idea for the URL field is not a required field. However, under your suggestion, these fields are forced to be required in logic. Since we set the formula for the validation in the field, if user can choose not to insert, it become a null value and does not pass the validation rule.
Any other method can perform validation check in apex code value, but not in field setting value? Thank you very much.
VineetKumarVineetKumar
Just put a check in the validation :
IF(AND(NOT(ISBLANK(URLfield__c)), REGEX(URLfield__c,"^((http|https)://)??(www[.])??([a-zA-Z0-9]|-)+?([.][a-zA-Z0-9(-|/|=|?)??]+?)+?$")),false,true)
Alluri VarmaAlluri Varma

Hi I am looking for the SF validation rule for below code.Can someone help.. Ref link: https://stackoverflow.com/questions/37013313/how-to-check-if-valid-facebook-url-before-submit/37013467#37013467


function validateUrl() {
  url = $("#FacebookUrl").val();
  var pattern = /^(?:(?:http|https):\/\/)?(?:www.)?facebook.com\/(?:(?:\w)*#!\/)?(?:pages\/)?(?:[?\w\-]*\/)?(?:profile.php\?id=(?=\d.*))?([\w\-]*)?$/;
  if(pattern.test(url)) {
    alert("Correct URL");
  }
  else {
    alert("Incorrect URL");
  }
  return pattern.test(url);
}