LoginSignup
0
1

More than 3 years have passed since last update.

Laravel で バリデーションルールに Twitter のTweetのルールを使う

Posted at

やりたいこと

Twitter連携アプリを作成しており、入力をフロントでtwitter-text.jsを使ってバリデーションしましたが、サーバー側でも行いたい。

公式からはPHP向けのが公開されていませんが、PHP向けのを公開していただけている方がいるので、ありがたく使わせていただきます。
メンテンナンス頻度も高いです。

インストール

composer require nojimage/twitter-text-php

Laravelで独自ルール作成

php artisan make:rule TwitterTextRule
TwitterTextRule
<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use Twitter\Text\Parser;

class TwitterTextRule implements Rule
{
    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        $parser = new Parser();
        $parse_result = $parser->parseTweet($value);
        //weightedLengthに文字数、validにツイートできるか
        return $parse_result->valid;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return ':attributeはTweetできません。';
    }
}

あとはバリデーションルールに指定する

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1