如何在 WordPress 联系表单 7 插件中创建自定义手机号码验证是否可能,请帮助我。 实际上我只想只允许有效的手机号码,此字段不接受任何其他字符,例如 9708644571
// Phone number validation : format and 10 digits
// Add code in your functions.php file
function custom_contact_validation_filter( $result, $tag ) {
// 'contact': is name of tag in contact form
if ( 'contact' == $tag->name ) {
$re_format = '/^[0-9]{10}+$/'; //9425786311
$your_contact = $_POST['contact'];
if (!preg_match($re_format, $your_contact , $matches)) {
$result->invalidate($tag, "Enter 10 digits only" );
}
}
return $result;
}
add_filter( 'wpcf7_validate_text*', 'custom_contact_validation_filter', 10, 2 );
add_filter( 'wpcf7_validate_text', 'custom_contact_validation_filter', 10, 2 );
要使用电话号码验证,您需要按照下面给出的示例输入号码字段。
[number* your-number min:9 max:10 step:3 class:required "40"]
参考链接:CF7
如果你想对手机号码使用自定义验证,那么你也可以使用 jQuery。
就像这样:
$('.wpcf7-form .custom-field-class input').on('keypress', function(e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && (e.which < 43 || e.which > 57)) {
return false;
}
});
将此文件放置在表单存在的页面模板中、footer.php 或自定义 js 文件中。
请将
custom-field-class
替换为您的输入字段包装类,或者您可以根据您的要求修改您的类和输入名称。
希望这对您有帮助。
To validate an Australian phone number in Contact Form 7:
Add Phone Field in CF7:
<div class="form-fields-wrapper">
<label>PHONE NUMBER <span>*</span></label>
[text* phone-number class:phone-number id:phone-number minlength:10 maxlength:10]
</div>
Add jQuery Script in Footer:
<script>
jQuery(function($){
var phoneNumberField = $('#phone-number');
phoneNumberField.on('input', function() {
var currentValue = $(this).val().replace(/[^0-9]/g, '');
phoneNumberField.next('.phone-error').remove();
if (currentValue && !currentValue.startsWith('04')) {
phoneNumberField.after('<div class="phone-error" style="color: red;">Please enter a valid Australian number.</div>');
} else {
$(this).val(currentValue);
}
});
});
</script>
Explanation: This script restricts input to numbers only and shows an error if the number doesn’t start with "04".