Validating Text Entry with Regular Expressions

One of the earliest applications of JavaScript in web browsers was to perform prevalidation of form text fields prior to submitting the form to the server. The purpose of prevalidating in the browser is to provide instant feedback to obvious form entry errors, such as missing required fields or an incorrect data format. It is still necessary to perform validations again on the server for security and data integrity reasons, but by saving repeated roundtrips between browser and server to fix several entry errors, the user experience is improved with client-side validation. JavaScript has offered regular expression support for a long time now, making it easier to compare text entry against expected patterns, such as North American telephone numbers, US zip codes, and email addresses.

Surprisingly, general-purpose regular expressions have arrived late to the iOS platform, becoming first available in iOS 4. Therefore, this section applies only to apps that will be distributed with iOS 4 as the minimum platform. This section also assumes that you are familiar with regular expression syntax.

In JavaScript, regular expression patterns are allowed as arguments for a variety of String object methods, such as match(), replace(), and split(). This is in addition to a regular expression object instance, which contains a pattern you assign to it and offers methods—exec() and test()—to uncover matches in strings. Therefore, in JavaScript you can discover ...

Get Learning the iOS 4 SDK for JavaScript Programmers now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.