Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to use Validation in cakephp 3.0?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 158
    Comment on it

    Hello Reader's ,

    Hope your are doing good today.

    Today we will learn about Validation in CakePHP 3.0 and how we can use validator in our applications. Data validation is an important part of any of the application. With the help of Validator. We can sure that the data input by a user is valid or not.


    First. set the validation rule in a model.

    //"src/Model/Table/"
    
    
    use Cake\Validation\Validator;
    
    $validator = new Validator();	

     

    After creating validator class now you can  set rules for the fields you want to validate.

    $validator
        ->requirePresence('title')
        ->notEmpty('title', 'Please fill this field')
        ->add('title', [
            'length' => [
                'rule' => ['minLength', 10],
                'message' => 'Titles need to be at least 10 characters long',
            ]
        ])
        ->requirePresence('body')
        ->add('body', 'length', [
            'rule' => ['minLength', 50],
            'message' => 'Articles must have a substantial body.'
        ]);

     

    Another way to Validate field by validationDefault function in your model.

     public function validationDefault(Validator $validator)
        {
            $validator
                ->notEmpty('title')
                ->requirePresence('title')
                ->notEmpty('body')
                ->requirePresence('body');
    
            return $validator;
        }

    I hope this will help you.Please feel free to give us your feedback in comments.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: