ThinkPHP Form Automatic Validation Instance

  • 2021-07-21 07:59:34
  • OfStack

This paper describes the implementation method of ThinkPHP form automatic verification with an example. Share it for your reference. The specific methods are as follows:

The sample code is implemented using the TP 3.2 framework. The specific code is as follows:

public function add_post(){
        // Verification rule
        $rule=array(
            array('name','require',' Please enter a name ',1),// You must verify that name
        );
 
        $m=M('user');
 
        // Get name,sex,contact Data to the model and validate
        if(!$m->field('name,sex,contact')->validate($rule)->create())
            $this->error($m->getError());
 
        $result=$m->add();
 
        if(!$result)
            $this->error(' Add failed ');
 
        $this->success(' Successful addition ',U('dir'));
}

The verification rules can also be written into the model, but the author feels a little troublesome. 1. Sometimes different pages have different verification methods. 2. Seeing the code in this add_post event, it is clear what data to receive and how to verify the data can have a general understanding at the first eye, so this method is summarized.

I hope this article is helpful to everyone's ThinkPHP program development.


Related articles: