The validation for email alerts me but when I click Ok it saves the record to salesforce

Here is the code:

<apex:page controller="myAudit">
  <script type="text/javascript">
     function validate() { 
            var ex= document.getElementsByClassName('email')[0].value;
            var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/i;
            var a = re.test(email);
                  alert("re.text_" + a);
            if (a == true)
             { alert('Valid email address'); }
            else { alert('Invalid email address'); }                  

    <apex:form id="audit">
        <apex:pageblock >
          <apex:pageblockSection columns="1">
            <p><apex:inputText value="{!account}" label="Account"/></p>
            <apex:inputText id="Survey" value="{!txtSurvey}" label="SurveyName"/>
            <apex:inputText id="email" value="{!email}" Label="Email" styleClass="examNote"/>
              <apex:commandButton action="{!save}" onclick="validate();" value="save"/>

  • 1
    You should just use a Validation Rule...
    – Adrian Larson
    Apr 20, 2017 at 17:36
  • Never count on just client side validation. Javascript can be disabled.
    – Adrian Larson
    Apr 20, 2017 at 18:13

1 Answer 1


Modify your javascript function like below:

if (a == true)
             { alert('Valid email address'); 
return true;
            else { alert('Invalid email address');
return false:

Also modifing command button. Add return validate()

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

Hope it helps!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.