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
Ashok.ForceAshok.Force 

How to stop the form submission if there is any javascript validation error?

Hi,

   I have  the following Apex Page where the form shouldn't submit if there is any validation error.

 

<apex:page showHeader="false" sidebar="false" standardController="Lead"
    extensions="Beneficiary">


    <h1>NGO membership form</h1>

    <apex:form id="myform" styleClass="standard-form"
        enctype="multipart/form-data">

        <apex:outputText value="Organisation" />
        <apex:inputText value="{!Lead.Company}" label="Organisation"
            required="true" id="organisation" />
        <br></br>
        <apex:outputText value="Email" />
        <apex:inputText value="{!Lead.Email__c}" label="Email" required="true"
            id="email" />
        <br></br>
        <apex:outputText value="LastName" />
        <apex:inputText value="{!Lead.LastName}" label="LastName"
            required="true" id="lastname" />
        <br></br>

        <apex:commandButton value="Submit" onclick="validate()" immediate="false"/>
    </apex:form>


    <script>
function validate()
{

    var a = document.getElementById('{!$Component.myform.lastname}').value;
    if(a == null || a.length == 0)
    {
         alert("Last name is a Mandatory Field");
         return null;
    }

}
</script>

</apex:page>

 

If the lastname is blank. I'm getting the validation error. But the form still submits. How to stop the form submission if there is any validation error?

Best Answer chosen by Admin (Salesforce Developers) 
BritishBoyinDCBritishBoyinDC

This works for me

 

<apex:commandButton onclick="return validate();" action="{!save}" value="Submit"/>

All Answers

SamuelDeRyckeSamuelDeRycke

Doesn't work that way ... to my knowledge you should:

 

Or you do javascript validation on events based on your inputelements, for instance keydown, loss of focus, selected option etc that kind of thing.

 

Or you rely in the force validation ... based on your field configuration, validation rules and using apex page messges in your controller.

 

 

Gunners_23Gunners_23

Instead of returning null like in controller use return false then it will prevent it from submitting the form

 

 <script>
function validate()
{

    var a = document.getElementById('{!$Component.myform.lastn

ame}').value;
    if(a == null || a.length == 0)
    {
         alert("Last name is a Mandatory Field");
         return false;
    }

}
</script>

Ashok.ForceAshok.Force

Even after adding return false still the form submits and calls the controller method

Ashok.ForceAshok.Force

This is my commandButton code

 

<apex:commandButton action="{!save}" onclick="validate()" value="Submit" />

Gunners_23Gunners_23

are you sure its calling the controller method? Did you override the save method in extension? if so could you pls post the same

Ashok.ForceAshok.Force

public with sharing class Beneficiary {
    
    private Lead lead;
    
    private String parentId { set; get; }
    
    public Attachment attachment1
    {
          get
          {
              if (attachment1 == null)
              {
                attachment1 = new Attachment();
              }
              return attachment1;
        }
          
          set;
   }
   
   public Attachment attachment2
    {
          get
          {
              if (attachment2 == null)
              {
                attachment2 = new Attachment();
              }
              return attachment2;
        }
          
          set;
   }
   
   public Attachment attachment3
    {
          get
          {
              if (attachment3 == null)
              {
                attachment3 = new Attachment();
              }
              return attachment3;
        }
          
          set;
   }
   
   public Attachment attachment4
    {
          get
          {
              if (attachment4 == null)
              {
                attachment4 = new Attachment();
              }
              return attachment4;
        }
          
          set;
   }
   
   public Attachment attachment5
    {
          get
          {
              if (attachment5 == null)
              {
                attachment5 = new Attachment();
              }
              return attachment5;
        }
          
          set;
   }
 
    private ApexPages.StandardController controller {get; set;}
    
    public Beneficiary(ApexPages.StandardController controller)
    {
        this.parentId   = controller.getId();
        
        this.controller = controller;
        
        this.lead = (Lead)controller.getRecord();
    }
    
    private boolean isValidUrl(string url)
    {
        
        //String regexp = '/(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/';
        
        String regexp = '([\\d\\w-.]+?\\.(a[cdefgilmnoqrstuwz]|b[abdefghijmnorstvwyz]|c[acdfghiklmnoruvxyz]|d[ejkmnoz]|e[ceghrst]|f[ijkmnor]|g[abdefghilmnpqrstuwy]|h[kmnrtu]|i[delmnoqrst]|j[emop]|k[eghimnprwyz]|l[abcikrstuvy]|m[acdghklmnopqrstuvwxyz]|n[acefgilopruz]|om|p[aefghklmnrstwy]|qa|r[eouw]|s[abcdeghijklmnortuvyz]|t[cdfghjkmnoprtvwz]|u[augkmsyz]|v[aceginu]|w[fs]|y[etu]|z[amw]|aero|arpa|biz|com|coop|edu|info|int|gov|eu|ar|mil|museum|name|net|org|pro)(\\b|\\W(?<!&|=)(?!\\.\\s|\\.{3}).*?))(\\s|$)';
        
        Pattern MyPattern = Pattern.compile(regexp);
        
        // Then instantiate a new Matcher object "MyMatcher"
        Matcher MyMatcher = MyPattern.matcher(url);
        
        if(url == null || url.length() == 0)
        {
            return true;
        }
        else if(!MyMatcher.matches())
          {
             return false;
         }
          else
          {
              return true;
          }
      return true;
    }
    
    private boolean isValidEmail(String email)
    {
        String emailRegex = '([a-zA-Z0-9_\\-\\.]+)@((\\[a-z]{1,3}\\.[a-z]{1,3}\\.[a-z]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})';
        Pattern MyPattern = Pattern.compile(emailRegex);
        
        // Then instantiate a new Matcher object "MyMatcher"
        Matcher MyMatcher = MyPattern.matcher(email);
        
        if(email == null || email.length() == 0)
        {
            return true;
        }
        else if (!MyMatcher.matches())
        {
            return false;
        }
        else
        {
            return true;
        }
    }
    

    
    public PageReference validateForm()
    {
        system.debug('validateFields called : ' + lead.List_Account_on_Website__c);
        
        if(!lead.List_Account_on_Website__c)
        {
            lead.List_Account_on_Website__c.addError('Please check this option');
            ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.FATAL,'Please check this option');
            ApexPages.addMessage(myMsg);
              
        }
        
        return null;
    }
        
    public PageReference save()
    {
        if(lead.Company == null || lead.Company.length() == 0)
        {
            system.debug('lead.Company   : ' + lead.Company);
            lead.company.addError('Enter the Valid Company');
              return  null;
        }
        
        
        if(!isValidEmail(lead.email__c))
        {
            //ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.FATAL,'Please Enter the Email Address.');
            //ApexPages.addMessage(myMsg);
            lead.email.addError('Enter the Valid Email');
              return  null;
        }
        else
        {
            lead.email = lead.email__c;
                    
            insert lead;
            
            Lead leadObj = [select Id from Lead where Lead.email__c = :lead.email] ;  
            
            /*
            // Code to send email when the application added to salesforce
            
            EmailTemplate et = [select Id,Name,Subject,body from EmailTemplate where name = 'Leads_Web_to_Lead_Admin_Alert'];
            User usr = [select u.Id, u.email, u.name from User u where u.email = 'ashok.chandragiri@thomsonreuters.com'];
            
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            
            List<string> aoMail = new List<string>();
            aoMail.add(usr.email);
            
            mail.setTemplateId(et.Id);
            mail.setToAddresses(aoMail);
            mail.setTargetObjectId(leadObj.Id);
            SingleEmailMessage[] messages = {mail};
            Messaging.sendEmail(mail);
            
            */
            if(attachment1.Body != null)
            {
                attachment1.OwnerId = UserInfo.getUserId();
                attachment1.ParentId = leadObj.id;
                attachment1.IsPrivate = true;
            }
            
            if(attachment2.Body != null)
            {
                attachment2.OwnerId = UserInfo.getUserId();
                attachment2.ParentId = leadObj.id;
                attachment2.IsPrivate = true;
            }
            if(attachment3.Body != null)
            {
                attachment3.OwnerId = UserInfo.getUserId();
                attachment3.ParentId = leadObj.id;
                attachment3.IsPrivate = true;
            }
            if(attachment4.Body != null)
            {
                attachment4.OwnerId = UserInfo.getUserId();
                attachment4.ParentId = leadObj.id;
                attachment4.IsPrivate = true;
            }
            if(attachment5.Body != null)
            {
                attachment5.OwnerId = UserInfo.getUserId();
                attachment5.ParentId = leadObj.id;
                attachment5.IsPrivate = true;
            }
            try {
        
                if(attachment1.Body != null)
                {
                      insert attachment1;
                }
                  
                  if(attachment2.Body != null)
                {
                      insert attachment2;
                }
                
                if(attachment3.Body != null)
                {
                      insert attachment3;
                }
                
                if(attachment4.Body != null)
                {
                      insert attachment4;
                }
                
                if(attachment5.Body != null)
                {
                      insert attachment5;
                }
            }
            catch (DMLException e)
                {
                ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error uploading attachment'));
                return null;
            }
            finally
            {
                  attachment1 = new Attachment();
                  attachment2 = new Attachment();
                  attachment3 = new Attachment();
                  attachment4 = new Attachment();
                  attachment5 = new Attachment();
            }
 
            
            PageReference pageRef= new PageReference('/apex/confirm');
        
            return pageRef;
        }
    }
    
     public static testMethod void testBeneficiary(){
       
        TestUtilities tu = TestUtilities.generateBeneficiaryTest();
        
        Test.startTest();
        
        ApexPages.StandardController sc = new ApexPages.StandardController(tu.aLead);
        
        Beneficiary beneficiary = new Beneficiary(sc);
        
        beneficiary.save();
        
        beneficiary.isValidEmail('test@test.com');
        
        beneficiary.isValidEmail(null);
        
        Test.stopTest();
        
     }
    
}

BritishBoyinDCBritishBoyinDC

This works for me

 

<apex:commandButton onclick="return validate();" action="{!save}" value="Submit"/>

This was selected as the best answer
Ashok.ForceAshok.Force

It works for the first time.

 

But If you click the submit button again then it calls the controller

 

check this link for a demo

 

http://trustlawportal.developer.cs7.force.com/leadtest

Ashok.ForceAshok.Force

Sorry its working fine. I found the problem in my code.

 

Thanks for your help

Nash79Nash79
How did you fix it Ashok?