The form field validation trick they don’t want you to know

Yes, that was a purposefully click-bait headline.

One of the most frustrating things for users is unclear or unintuitive form constraints. My personal pet peeve are phone number, credit card, or SSN/ EIN fields which ask for numeric-only entry. While it may very well be necessary that your field use only numeric data, you don’t have to offload that requirement to the user. If, for instance, your field collects a North American telephone number, you know that a valid telephone number consists of 10 numeric characters. Instead of offloading the numerics-only constraint to the user, you can easily and simply strip the non-numeric characters yourself before then validating the string length. This seems far more intelligent and certainly more user-friendly.

Here’s how

Because so many things require string manipulation most, if not all, programming languages have some mechanism of finding, substituting, or removing sub-strings, often through the use of Regular Expressions. Here are some examples, shamelessly stolen from Code Codex:

C


#include <string.h>  
  
while (i != strlen (buff))  
{  
    if ((buff[i] >= 48) && (buff[i] <= 57))  
    {  
        buff_02[j] = buff[i];  
        i++;  
        j++;  
    }  
    else  
    {  
        i++;  
    }  
}

Haskell


removeNonNumbers :: String -> String
removeNonNumbers = filter Char.isDigit

Java


static String numbersOnly(String s) {  
    return s.replaceAll("\\D","");  
}  

JavaScript

  
s.replace(/\D/g, "");
  

Perl


s{\D}{}g; # remove all non-digits

PHP


preg_replace('/\D/', '', $string);  

Python


import re  
re.sub("\D", "", s)  

Ruby


s.gsub(/\D/, "")
  
If you are interested in learning about the next generation in Web Accessibility Testing, give Tenon.io a try.
If you or your organization need help with accessibility consulting, strategy, or accessible web development, email me directly at karl@karlgroves.com or call me at +1 443-875-7343. Download Resume [MS Word]

Post a Comment