APEX-为什么我的输入验证无效?

问题描述

我正在使用联系人搜索页面,但遇到了问题。我的控制台没有错误,但是当我运行搜索时,不会生成结果,并且会提示所有输入验证错误。

例如:

Jane Grey

The Search for Jane Grey

这是我的VisualForce页面:

<apex:page id="ContactPage" controller="Ctrl_ContactSearch">
  
     
      <apex:tabPanel id="ContactPanel">
             
        <apex:tab id="ContactTab" label="Contact Search"> 
            
                  
          <apex:form id="ContactForm">

              
              <!-- Input Fields -->
            <apex:pageBlock title="Contact Search Page" id="ContactBlock">
                                
                <apex:pageBlockSection id="contact-table" columns="3">
                                     
                    <apex:pageBlockSectionItem id="NameInputBlock">                    
                        <apex:outputLabel value="Name" />
                        <apex:inputText id="NameInputField" value="{!name}" />                   
                    </apex:pageBlockSectionItem>
    
                    <apex:pageBlockSectionItem id="PhoneInputBlock">                    
                        <apex:outputLabel value="Phone" />
                        <apex:inputText id="PhoneInputField" value="{!phone}" />                   
                    </apex:pageBlockSectionItem>
                    
                    <apex:pageBlockSectionItem id="EmailInputBlock">                    
                        <apex:outputLabel value="Email" />
                        <apex:inputText id="EmailInputField" value="{!email}" />                   
                    </apex:pageBlockSectionItem>
                       
                </apex:pageBlockSection>   
                
                
                 <!-- Buttons -->
                <apex:pageBlockButtons location="bottom">
                    <apex:commandButton value="Search Contacts" action="{!searchContacts}"  />
                    <apex:commandButton value="Clear Fields" action="{!ClearFields}" />   
                </apex:pageBlockButtons>
                
             </apex:pageBlock>
            

  
            <!-- Results Display -->
            <apex:pageBlock title="Results" rendered="{!contacts.size!=0}" > 
                
                <apex:pageBlockSection >
                
                    <apex:pageBlockTable value="{!contacts}" var="c" id="contact-table">
                            
                            <apex:column >
                                <apex:facet name="header">Name</apex:facet>
                                {!c.Name}
                            </apex:column>
        
                            <apex:column >
                                <apex:facet name="header">Phone Number</apex:facet>
                                {!c.Phone}
                            </apex:column>
                            
                            <apex:column >
                                <apex:facet name="header">Email</apex:facet>
                                {!c.Email}
                            </apex:column>
                            
                        </apex:pageBlockTable>
                    
                </apex:pageBlockSection>
   
            </apex:pageBlock>
              
              
              
          <!-- Error Display -->    
          <apex:pageBlock title="Errors" id="ErrorSection" >
              
                <apex:pageMessages id="ErrorsListing">
                  
                </apex:pageMessages>
              
          </apex:pageBlock>
              
              
              
                                                    
           </apex:form>

            
        </apex:tab>
                  
      </apex:tabPanel>      
        
    <script type = "text/javascript">
    
        var name = document.getElementByID("name");
        var phone = document.getElementByID("phone");
        var email = document.getElementByID("email");
        
    </script>
    
</apex:page>

这是我的控制人:

public with sharing class Ctrl_ContactSearch
{
    public List<Contact> contacts { get; set; }
    
    public String name { get; set; }
    public String phone { get; set; }
    public String email { get; set; }   
       
    public integer MatchingContacts { get; set; }  
    
    public boolean ErrorsPresent = false;
    public boolean Error_NoResults = false;
    public boolean Error_FieldsEmpty = false;
    public boolean Error_NameSyntax = false;
    public boolean Error_PhoneSyntax = false;
    public boolean Error_EmailSyntax = false;
    
    
   /* Name Input Validation Regex*/
   public static Boolean ValidationName (String name)
            {
                Boolean NameIsValid = false;
                
              
                String nameRegex = '/^[a-zA-Z][a-zA-Z0-9]*(_[a-zA-Z0-9]+)*(__[cC])?$/';
                Pattern PatternName = Pattern.compile(nameRegex);
                Matcher nameMatcher = PatternName.matcher(name);
                
                if (nameMatcher.matches())
                    {
                        NameIsValid = true;
                    } 
 
                return NameIsValid; 
            }
    
     
    /* Phone Input Validation Regex*/
    public static Boolean ValidationPhone (String phone)
            {
                Boolean PhoneIsValid = false;
                
               
                String phoneRegex = '//^\\(?([0-9]{3})\\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$//';
                Pattern PatternPhone = Pattern.compile(phoneRegex);
                Matcher phoneMatcher = PatternPhone.matcher(phone);
                
                if (phoneMatcher.matches())
                    {
                        PhoneIsValid = true;
                    } 
                   
                return PhoneIsValid;        
            }          
    
   
     /* Email Input Validation Regex*/
     public static Boolean ValidationEmail (String email)
            {
                Boolean EmailIsValid = false;
                
               
                String emailRegex = '/^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,3})+$//';
                Pattern PatternEmail = Pattern.compile(emailRegex);
                Matcher emailMatcher = PatternEmail.matcher(email);
                
                if (emailMatcher.matches())
                    {
                        EmailIsValid = true;
                    } 
                    
                return EmailIsValid;    
            }       
    
    

    
    /* Runs when "Clear Fields" button is pressed*/
    public void ClearFields()
            {
               name = '';
               phone = '';
               email = ''; 
            }
    
    
    /* Runs when "Search Contacts" button is pressed*/
    public PageReference searchContacts()
        {
                           
            /* Checks if input fields are empty*/
            if (name == '' && phone == '' && email == '')
                {
                    Error_FieldsEmpty = true;   
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Your fields are blank. Please enter your information in the remaining fields to proceed'));
                }         
            else 
                {
                    /* Checks Input Validation Results*/                      
                    if (ValidationName(name) == false) 
                         {      
                              Error_NameSyntax = true;
                              ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Inproper name format. Please enter name in following format : Firstname Lastname.'));
                          }
                                                                                 
                    if (ValidationPhone(phone) == false) 
                         {
                              Error_PhoneSyntax = true;
                              ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Inproper phone number format. Please enter number in following format : XXX-XXX-XXXX.'));
                          }
                    
                    if (ValidationPhone(email) == false) 
                         {   
                              Error_EmailSyntax = true;
                              ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Inproper email format. Please enter email in following format : XXX@emailprovider.com'));
                          }
                        
                    /* Runs if all Validation results are 'true'*/ 
                    if (ValidationName(name) == true && ValidationPhone(phone) == true && ValidationPhone(email) == true)
                        {
                              contacts = [select Name,Phone,Email from Contact where Name = :name or Phone = :phone or email = :email];
                              MatchingContacts = contacts.size();
                            
                              /* Checks if/how many matches were found from the search*/ 
                              if(MatchingContacts != 0)
                                  {  
                                     system.debug('There are currently ' + MatchingContacts + 'results found.' );
                                  }
                              
                              else
                                  {    
                                      Error_NoResults = false;
                                      ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'No matching Contacts were found.'));   
                                  }
                        }
                    
                   
                }
                    

              
             /* Displays "Error" field if any errors are found*/
            if (Error_NoResults == true || Error_FieldsEmpty == true || Error_NameSyntax == true || Error_PhoneSyntax == true || Error_EmailSyntax == true)
                {
                    ErrorsPresent = true;
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING,'There are errors present. Please read and follow instructions accordingly.'));                     
                }     
            
            
           return null;     
      }           
}

我这里怎么了?

由于某种原因,StackOverflow在不添加额外文本的情况下不允许我发表这篇文章。我将其放在此处以增加字数。

解决方法

第一,一些建设性的批评:

DRY原则要求您将验证方法合并为1。

2,看来您的正则表达式不好。根据验证的确切要求,您可以在下面尝试这些。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。

尝试这样的事情:

private string nameRegEx = '^[a-zA-Z][a-zA-Z0-9 ]+$';
private string emailRegEx = '^[a-zA-Z0-9._|\\\\%#~`=?&/$^*!}{+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}$';
private string phoneRegEx = '^(\\d{3}\\-\\d{3}-\\d{4})?$';

public static Boolean Validate (String str,String validation)
        {
            Boolean IsValid = false;
            
          
            Pattern Pattern = Pattern.compile(validation);
            Matcher Matcher = Pattern.matcher(str);
            
            if (Matcher.matches())
                {
                    IsValid = true;
                } 

            return IsValid; 
        }

此外,此函数返回Boolean。检查其返回值时,不需要等号运算符。只需使用if (Validate(name,nameRegex)) { ... }if (!Validate(email,emailRegex)) { ... }

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...