OLD | NEW |
| (Empty) |
1 // Copyright (c) 2013 The Chromium Authors. All rights reserved. | |
2 // Use of this source code is governed by a BSD-style license that can be | |
3 // found in the LICENSE file. | |
4 | |
5 #include "chrome/browser/autofill/validation.h" | |
6 | |
7 #include "base/string_util.h" | |
8 #include "base/utf_string_conversions.h" | |
9 #include "chrome/browser/autofill/autofill_regexes.h" | |
10 #include "chrome/browser/autofill/credit_card.h" | |
11 | |
12 namespace autofill { | |
13 | |
14 bool IsValidCreditCardNumber(const string16& text) { | |
15 string16 number = CreditCard::StripSeparators(text); | |
16 | |
17 // Credit card numbers are at most 19 digits in length [1]. 12 digits seems to | |
18 // be a fairly safe lower-bound [2]. | |
19 // [1] http://www.merriampark.com/anatomycc.htm | |
20 // [2] http://en.wikipedia.org/wiki/Bank_card_number | |
21 const size_t kMinCreditCardDigits = 12; | |
22 const size_t kMaxCreditCardDigits = 19; | |
23 if (number.size() < kMinCreditCardDigits || | |
24 number.size() > kMaxCreditCardDigits) | |
25 return false; | |
26 | |
27 // Use the Luhn formula [3] to validate the number. | |
28 // [3] http://en.wikipedia.org/wiki/Luhn_algorithm | |
29 int sum = 0; | |
30 bool odd = false; | |
31 for (string16::reverse_iterator iter = number.rbegin(); | |
32 iter != number.rend(); | |
33 ++iter) { | |
34 if (!IsAsciiDigit(*iter)) | |
35 return false; | |
36 | |
37 int digit = *iter - '0'; | |
38 if (odd) { | |
39 digit *= 2; | |
40 sum += digit / 10 + digit % 10; | |
41 } else { | |
42 sum += digit; | |
43 } | |
44 odd = !odd; | |
45 } | |
46 | |
47 return (sum % 10) == 0; | |
48 } | |
49 | |
50 bool IsValidCreditCardSecurityCode(const string16& text) { | |
51 if (text.size() < 3U || text.size() > 4U) | |
52 return false; | |
53 | |
54 for (string16::const_iterator iter = text.begin(); | |
55 iter != text.end(); | |
56 ++iter) { | |
57 if (!IsAsciiDigit(*iter)) | |
58 return false; | |
59 } | |
60 return true; | |
61 } | |
62 | |
63 bool IsValidEmailAddress(const string16& text) { | |
64 // E-Mail pattern as defined by the WhatWG. (4.10.7.1.5 E-Mail state) | |
65 const string16 kEmailPattern = ASCIIToUTF16( | |
66 "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@" | |
67 "[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*$"); | |
68 return MatchesPattern(text, kEmailPattern); | |
69 } | |
70 | |
71 bool IsValidZip(const string16& value) { | |
72 const string16 kZipPattern = ASCIIToUTF16("^\\d{5}(-\\d{4})?$"); | |
73 return MatchesPattern(value, kZipPattern); | |
74 } | |
75 | |
76 } // namespace autofill | |
OLD | NEW |