php || 数据验证类

1. 验证字符串长度

类(length_class.php):

<?php
        class Length{
    
    
                protected $min;
                protected $max;

                //$arr的输入格式为一个数组,如['min'=>19,'max'=>29]
                function __construct($arr){
    
    
                        $this->min = $arr["min"];
                        $this->max = $arr["max"];
                }

                //如果$value字符串长度在min和max范围内,返回true
                function validate($value){
    
    
                        if(strlen($value)>=$this->min && strlen($value)<=$this->max){
    
    
                                return true;
                        }else{
    
    
                                return false;
                        }
                }
        }
?>

调用(length.php):

<?php
        require_once("length_class.php");
        $ob = new Length(["min"=>10,"max"=>20]);
        $re = $ob->validate("sjjsjsjjj");
        if($re){
    
    
                echo "字符串长度符合要求";
        }else{
    
    
                echo "字符串长度不符合要求";
        }
?>

图:
在这里插入图片描述

2. 数字范围验证

类(age_class.php):

<?php
        class Length{
    
    
                protected $min;
                protected $max;

                //$arr的输入格式为一个数组,如['min'=>19,'max'=>29]
                function __construct($arr){
    
    
                        $this->min = $arr["min"];
                        $this->max = $arr["max"];
                }

                //如果$value在min和max的范围中,返回true
                function validate($value){
    
    
                        if($value>=$this->min && $value<=$this->max){
    
    
                                return true;
                        }else{
    
    
                                return false;
                        }
                }
        }
?>

调用(age.php):

<?php
        require_once("age_class.php");
        $ob = new Length(["min"=>10,"max"=>20]);
        $re = $ob->validate(24);
        if($re){
    
    
                echo "年龄在10到20范围内";
        }else{
    
    
                echo "年龄不在规定范围内";
        }
?>

图:
在这里插入图片描述

Guess you like

Origin blog.csdn.net/weixin_45703155/article/details/107741321
php