• Hi, so I have a form with these as the shortcode

    [text* your-name class:form-control]
    [text* your-phone minlength:10 maxlength:10 class:form-control class:phonetxt]

    And in my theme’s functions.php

    function cf7_custom_form_validation($result,$tag) {
    	$type = $tag['type'];
    	$name = $tag['name'];
    
    	if($type == 'text*' && $_POST[$name] == ''){
    			$result['valid'] = false;
    			//$result['reason'][$name] = wpcf7_get_message( 'invalid_required' );
    			$result['reason'][$name] = "fill me";
    	}
    
    	if($name == "your-name") {
    		$yourname = $_POST['your-name'];
    		if(empty($yourname)) {
    			$result['valid'] = false;
    			$result['reason'][$name] = 'Please enter your name';
    		}
    	}
    	if($name == "your-phone") {
    		$yourphone = trim($_POST['your-phone']);
    
    		if(empty($yourphone)) {
    			$result['valid'] = false;
    			$result['reason'][$name] = 'Please enter your phone';
    		} elseif(strlen($yourphone)<10) {
    			$result['valid'] = false;
    			$result['reason'][$name] = 'Phone is invalid';
    		} elseif(strlen($yourphone)>10) {
    			$result['valid'] = false;
    			$result['reason'][$name] = 'Phone is invalid';
    		} else {
    			$first3 = substr($yourphone, 0, 3);
    			$ok= array(134,135,136,137,138,139,147,150,151,152,153,155,156,157,158,159,181,182,183,185,186,187,188,189,130,131,132,133);
    			if(!in_array($first3,$ok)) {
    				$result['valid'] = false;
    				$result['reason'][$name] = 'Phone must start with 134,135,136,137,138,139,147,150,151,152,153,155,156,157,158,159,181,182,183,185,186,187,188,189, 130,131,132,133';
    			}
    		}
    	}
    return $result;
    }
    //add filter for text field validation
    add_filter('wpcf7_validate_text','cf7_custom_form_validation', 10, 2);
    add_filter('wpcf7_validate_text*', 'cf7_custom_form_validation', 10, 2);

    But I can’t seem to make it work. When I hit the submit button, it just shows the default error message.
    Please advice if i did anything wrong?

    Thank you!

    https://wordpress.org/plugins/contact-form-7/

Viewing 1 replies (of 1 total)
Viewing 1 replies (of 1 total)
  • The topic ‘Custom Validation’ is closed to new replies.