A. The regex does not anchor start and end, allowing invalid matches
B. The regex should be enclosed in quotes
C. The message key is misspelled
D. The validates method is missing a colon before phone
Solution
Step 1: Review the regex pattern
The regex /\d{10}/ matches any 10 digits anywhere in the string, not necessarily the whole string.
Step 2: Understand validation implications
Without anchors \A and \z, strings with extra characters before or after 10 digits will pass incorrectly.
Final Answer:
The regex does not anchor start and end, allowing invalid matches -> Option A
Quick Check:
Regex anchors needed for exact match [OK]
Hint: Always anchor regex with \A and \z for full string match [OK]
Common Mistakes:
Forgetting to anchor regex start/end
Assuming regex in quotes is required
Misspelling keys like message or validates
5. You want to validate a postal code that must be exactly 5 digits or 5 digits followed by a dash and 4 digits (like '12345' or '12345-6789'). Which validation is correct?
hard
A. validates :postal_code, format: { with: /\A\d{5}-\d{4}\z/, message: "invalid postal code" }
B. validates :postal_code, format: { with: /\d{5}(-\d{4})?/, message: "invalid postal code" }
C. validates :postal_code, format: { with: /\A\d{9}\z/, message: "invalid postal code" }
D. validates :postal_code, format: { with: /\A\d{5}(-\d{4})?\z/, message: "invalid postal code" }
Solution
Step 1: Understand the postal code formats
Valid formats are 5 digits alone or 5 digits plus dash and 4 digits.
Step 2: Analyze regex options
validates :postal_code, format: { with: /\A\d{5}(-\d{4})?\z/, message: "invalid postal code" } uses anchors \A and \z and allows 5 digits with optional dash and 4 digits. validates :postal_code, format: { with: /\d{5}(-\d{4})?/, message: "invalid postal code" } lacks anchors, allowing partial matches. validates :postal_code, format: { with: /\A\d{5}-\d{4}\z/, message: "invalid postal code" } requires dash and 4 digits always, disallowing 5-digit only. validates :postal_code, format: { with: /\A\d{9}\z/, message: "invalid postal code" } requires exactly 9 digits, no dash.
Final Answer:
validates :postal_code, format: { with: /\A\d{5}(-\d{4})?\z/, message: "invalid postal code" } -> Option D
Quick Check:
Anchored regex with optional group = validates :postal_code, format: { with: /\A\d{5}(-\d{4})?\z/, message: "invalid postal code" } [OK]
Hint: Use anchors and optional group for flexible exact match [OK]
Common Mistakes:
Omitting anchors causing partial matches
Forcing dash and extra digits when optional
Using wrong digit counts or missing optional group
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.