我正在处理一个联系人搜索页面,遇到了一个问题。我的控制台没有错误,但当我运行搜索时,不会生成结果,并且会提示所有输入验证错误。
例如:
Jane Grey
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。
第二,看起来您的正则表达式不太好。根据验证的确切要求,您可以尝试以下操作。。。随意取自论坛上对其他问题的其他回复,就像这个。。。(我绝非Regex专家(
试试这样的东西:
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)) { ... }