I recently decided to tackle a problem that had been bothering me in regards to the cforms II WordPress plugin, by Delicious Days. cforms is a hefty plugin that makes web form creation, administration, and tracking fairly easy. It has some annoyances, but for the most part, it does it’s job well. I was using WordPress v3.2.1 with cforms v12.2.
I was assigned a to-do asking me to find out why a form was only validating the email and captcha fields, when there were 3 other fields (‘First Name,’ ‘Last Name,’ and ‘Phone’) designated as required in the form’s settings. Upon further investigation, I found that the problem only occurs when the single line fields had the ‘auto-clear’ box checked, otherwise it validated against all fields. The ‘auto-clear’ checkbox will display a default value, like ‘Name,’ in the field until
onfocus, then it removes the value so the user can enter something. If the user doesn’t, the default value will reappear
To fix this, I had to use the regex option for the single line of text. This regex will be compared to the entered value when the form is submitted. If there’s a match, the form validation will fail and an error will be displayed.
I hopped over to the HiFi Regex Tester, a handy regex sandbox, and starting playing around. I came up with:
‘First Name’ is replaceable, as I checked it against ‘Last Name’ and ‘Phone’ with success.
Here’s why it works:
$will check the entire string.
(?!First Name$)This is the negative lookahead syntax that begin matching at the end of the string using a string of ‘First Name.’ Negative lookahead matches the search string where a not-matching pattern begins.
.*will match any single preceeding character 0 or more times.
Basically, cforms will use the regex to test and see if ‘First Name’ was entered into the single form field. If it was, it will not validate.
This has solved a lot of headaches in my daily work. If you know of any simpler or better ways to accomplish this validation, please comment.