键入时进行重力形式验证

时间:2019-01-30 12:26:48

标签: php forms validation gravity

您好,我有一个重力表格,可以使用日期下拉列表(必须超过16岁)验证年龄,所有方法都很好,但是仅当您转到下一页时才显示错误消息(多页表格) ,我要的是您选择日期后立即进行验证

    //Age Verification Apply National Insurance Number

    add_filter('gform_validation_1', 'verify_minimum_age');
    function verify_minimum_age($validation_result){
    // retrieve the $form
    $form = $validation_result['form'];
    // date of birth is submitted in 3 drop menus with a parent ID         of 31 in the format MM/DD/YYYY
    // change the 31 here to your field ID
    $dob_aray = rgpost('input_7');
    //if using a date drop down, the input is returned in an array as follows
    $dob_month = $dob_aray[0];
    $dob_day = $dob_aray[1];
    $dob_year = $dob_aray[2];
    //sidebar- some conditional logic to make sure that single digits are rendered with a 0 in front of them
    if($dob_month < 10){ $dob_month = 0 . $dob_month; }
    if($dob_day < 10){ $dob_day = 0 . $dob_day; }
    //ok, now feed the $dob variable using the parts of the array, arranged as YYYY-MM-DD
    //this is where we get away with using the date drop downs as opposed to the calendar!
    $dob = $dob_year . '-' . $dob_month . '-' . $dob_day;
    // this the minimum age requirement we are validating
    $minimum_age = 16;
    // calculate age in years like a human, not a computer, based on the same birth date every year
    $age = date('Y') - substr($dob, 0, 4);
    if (strtotime(date('Y-m-d')) - strtotime(date('Y') . substr($dob, 4, 6)) < 0){
    $age--;
    }
    // is $age less than the $minimum_age?
    if( $age < $minimum_age ){
    // set the form validation to false if age is less than the minimum age
    $validation_result['is_valid'] = false;
    // find field with ID of 31 and mark it as failed validation
    foreach($form['fields'] as &$field){
        // NOTE: replace 31 with the field you would like to mark invalid
        if($field['id'] == '7'){
            $field['failed_validation'] = true;
            $field['validation_message'] = "Sorry, you must be at least $minimum_age years of age and under 65 to apply.";
            break;
        }
    }
}
    // assign modified $form object back to the validation result
    $validation_result['form'] = $form;
    return $validation_result;
    }

1 个答案:

答案 0 :(得分:0)

您可以使用重力向导功能

https://gravitywiz.com/documentation/gravity-forms-limit-dates/

当然,这也可以使用js完成。如果这不是适合您的方式 我会为你写的