You need to sign in to do that
Don't have an account?
Matthew Harris 40
Why aren't my input validations working?
I'm working on a contact search page and I have a problem. My console has no errors but when I run a search, the results don't generate and all my input validation errors prompt.
For Example:
Here is my VisualForce Page:
What do I have wrong here?
For Example:
Here is my VisualForce Page:
<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>Here is my Controller
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 remainding 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; } }
What do I have wrong here?
You are seeing these errors because the input that have given didn't match the regex expressions that you are matching in the apex class. As a result, all the inputs are considered as invalid and you are getting these warnings or errors.
Please use the below link to validate the regex that you want to use for the proper formats:
https://regex101.com/
Once the proper regex is used, you will get the matching records.
Let me know if you need more help on this.
Thanks,
Abhishek Bansal.
All Answers
You are seeing these errors because the input that have given didn't match the regex expressions that you are matching in the apex class. As a result, all the inputs are considered as invalid and you are getting these warnings or errors.
Please use the below link to validate the regex that you want to use for the proper formats:
https://regex101.com/
Once the proper regex is used, you will get the matching records.
Let me know if you need more help on this.
Thanks,
Abhishek Bansal.
For email validation, I do see a mistake, you are calling validatePhone method on Email validation instead of validateEmail. Please correct this.
Regarding the name, please make sure in the site that space is not causing issue. If possible validate first name and last name separately. I don't see any issue with the name validation.
Apart from this everything looks fine.
Thanks,
Abhishek Bansal
Also I looked and didnt see them.
String firstName = name.split(' ')[0];
String lastName = name.split(' ')[1];
Now validate both these strings separately.
Thanks,
Abhishek Bansal
String nameRegex = '[a-zA-Z]*[\\s]{1}[a-zA-Z].*';
Thanks so much for your help Mr.Bansal! You alone are 10x more helpful than anyone I've spoken to at StackOverFlow!
Now I have one more favor to ask of you. In the 'Results' pageblock, I want to display the number of results found. I already the current number of matching contacts assigned to a integer: 'MatchingContacts'. How would I go about this?
You can add one outputText at the bottom of the page block:
Number of Results founds = {!MatchingContacts}
And thanks for your kind words. I am always happy to help others. You can also reach out to me directly in case you need any immediate assistance:
Gmail: abhibansal2790@gmail.com
Skype: abhishek.bansal2790
My Output Text:
<apex:outputText value="There are currently '{!MatchingContacts}' results found!" />
My Error
Unknown property 'Ctrl_ContactSearch.MatchingContacts'