请求将PHP正则表达式转换为适配jQuery验证的JavaScript代码
Convert Danish Phone Number Validation from PHP to jQuery Validation
Let's walk through adapting your Contact Form 7 PHP regex into a working jQuery Validation method step by step.
First, complete the reusable "regex" validation method you started. We just need to add the regex test and a small cleanup step for user input:
$.validator.addMethod("regex", function(value, element, regexp) { var re = new RegExp(regexp); // Trim whitespace to handle accidental leading/trailing spaces return this.optional(element) || re.test(value.trim()); });
Next, apply this method to validate Danish phone numbers using your adapted regex. Since JavaScript regex syntax matches PHP's PCRE almost exactly, we can use the pattern directly as a regex literal (cleaner than a string with escaped backslashes):
// Initialize validation on your form $("#your-contact-form-id").validate({ rules: { // Replace "phone" with your actual field name (e.g., "tel") phone: { regex: /^((\(?\+45\)?)?)(\s?\d{2}\s?\d{2}\s?\d{2}\s?\d{2})$/ } }, messages: { phone: { regex: "Please enter a valid Danish phone number (e.g., +45 12 34 56 78 or 12345678)" } } });
Key Details:
- The regex matches valid Danish formats:
- Optional country code:
+45,(+45), or no country code at all - 8 digits, which can be grouped with optional spaces (e.g.,
12 34 56 78) or written as a single string (12345678)
- Optional country code:
- The
.trim()ensures accidental leading/trailing spaces don't break validation - The
this.optional(element)check allows empty values if the field isn't marked as required
If you need to pass the regex as a string (e.g., from a config file), escape the backslashes properly:
regex: "^((\\(?\\+45\\)?)?)(\\s?\\d{2}\\s?\\d{2}\\s?\\d{2}\\s?\\d{2})$"
内容的提问来源于stack exchange,提问作者sebastian sledz
相关产品推荐
相关产品推荐

