You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请求将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)
  • 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:39:14