source

Laravel 유효성 검사 속성 "nice names"

goodcode 2022. 9. 19. 23:36
반응형

Laravel 유효성 검사 속성 "nice names"

"language > {language} > validation.php"의 검증 속성을 사용하여 읽기 적절한 이름(예: first_name > First name)으로 : 속성 이름(입력 이름)을 바꾸려고 합니다.사용법은 매우 간단해 보이지만 검증기에는 "멋진 이름"이 표시되지 않습니다.

이거 있어요.

'attributes' => array(
    'first_name' => 'voornaam'
  , 'first name' => 'voornaam'
  , 'firstname'  => 'voornaam'
);

오류를 표시하는 경우:

@if($errors->has())
  <ul>
  @foreach ($errors->all() as $error)
    <li class="help-inline errorColor">{{ $error }}</li>
  @endforeach
  </ul>
@endif

컨트롤러에서의 검증:

$validation = Validator::make($input, $rules, $messages);

$messages 배열:

$messages = array(
    'required' => ':attribute is verplicht.'
  , 'email'    => ':attribute is geen geldig e-mail adres.'
  , 'min'      => ':attribute moet minimaal :min karakters bevatten.'
  , 'numeric'  => ':attribute mag alleen cijfers bevatten.'
  , 'url'      => ':attribute moet een valide url zijn.'
  , 'unique'   => ':attribute moet uniek zijn.'
  , 'max'      => ':attribute mag maximaal :max zijn.'
  , 'mimes'    => ':attribute moet een :mimes bestand zijn.'
  , 'numeric'  => ':attribute is geen geldig getal.'
  , 'size'     => ':attribute is te groot of bevat te veel karakters.'
);

내가 뭘 잘못하고 있는지 누가 좀 말해줄래?속성 배열(언어)에서 : 속성 이름을 "nice name"으로 바꾸고 싶습니다.

감사합니다!

편집:

문제는 Laravel 프로젝트에 기본 언어를 설정하지 않았다는 것입니다.언어를 'NL'로 설정하면 위의 코드가 작동합니다.그러나 언어를 설정하면 해당 언어가 url에 표시됩니다.그리고 난 그게 싫으면 좋겠어.

다음 질문입니다.URL에서 언어를 삭제하거나 기본 언어가 표시되지 않도록 설정할 수 있습니까?

네, 몇 달 전만 해도 당신이 말한 "멋진 이름" 특성이 진짜 "문제"였어요.이제 이 기능이 구현되어 매우 간단하게 사용할 수 있기를 바랍니다.

간단하게 하기 위해서, 이 문제에 대처하기 위해서, 다음의 2개의 옵션을 분할합니다.

  1. 글로벌 아마도 더 널리 퍼질 것이다.이 접근방식은 여기서 매우 잘 설명되지만 기본적으로 응용 프로그램/언어/XX/검증을 편집해야 합니다.php validation file (XX는 검증에 사용하는 언어입니다.

    맨 아래에는 속성 배열이 표시됩니다.그것이 "nice name" 속성 배열입니다.당신의 예에 따라 최종 결과는 다음과 같습니다.

    'attributes' => array('first_name' => 'First Name')
    
  2. 이것이 Taylor Otwell이 이 에서 말한 것입니다.

    지금 Validator 인스턴스에서 setAttributeNames를 호출할 수 있습니다.

    그것은 완벽하게 유효하며, 소스 코드를 확인하면 알 수 있습니다.

    public function setAttributeNames(array $attributes)
    {
        $this->customAttributes = $attributes;
    
        return $this;
    }
    

    이 방법을 사용하려면 , 다음의 간단한 예를 참조해 주세요.

    $niceNames = array(
        'first_name' => 'First Name'
    );
    
    $validator = Validator::make(Input::all(), $rules);
    $validator->setAttributeNames($niceNames); 
    

자원.

Github에는 많은 언어 패키지가 준비되어 있는 정말 멋진 레포트가 있습니다.꼭 확인해 보세요.

이게 도움이 됐으면 좋겠다.

이 문제에 대한 정답은 앱/lang 폴더로 이동하여 검증을 편집하는 것입니다.파일 하단에 attributes라는 배열이 있습니다.

/*
|--------------------------------------------------------------------------
| Custom Validation Attributes
|--------------------------------------------------------------------------
|
| The following language lines are used to swap attribute place-holders
| with something more reader friendly such as E-Mail Address instead
| of "email". This simply helps us make messages a little cleaner.
|
*/

'attributes' => array(
    'username' => 'The name of the user',
    'image_id' => 'The related image' // if it's a relation
),

이 어레이는 이러한 속성명을 커스터마이즈하기 위해 구축되었다고 생각합니다.

라라벨 5.2부터...

public function validForm(\Illuminate\Http\Request $request)
{
    $rules = [
        'first_name' => 'max:130'
    ];  
    $niceNames = [
        'first_name' => 'First Name'
    ]; 
    $this->validate($request, $rules, [], $niceNames);

    // correct validation 

"속성" 배열에서 키는 입력 이름이고 값은 메시지에 표시할 문자열입니다.

다음과 같은 입력이 있는 경우의 예

 <input id="first-name" name="first-name" type="text" value="">

어레이(검증 중).php 파일)은 다음과 같습니다.

 'attributes' => array(
    'first-name' => 'Voornaam'),

나도 똑같은 걸 해봤는데 잘 되더라.이게 도움이 됐으면 좋겠다.

편집

, 라, 라, 라, 라, 파, 파, also, also, also, also, also, also, also, also, also, also, also, also, also, also, also, also, also, also, also, $errors->has()그게 문제일지도 몰라요

이와 같은 코드가 있는 경우 컨트롤러에서 이 검사를 수정하려면

return Redirect::route('page')->withErrors(array('register' => $validator));

에 '먹다', '먹다', '먹다'로 넘어가야 요.has() ' 키를 '레지스터'로 합니다.

@if($errors->has('register')
.... //code here
@endif

에러 메시지를 표시하는 또 다른 방법은 다음과 같습니다(Twitter Bootstrap을 설계에 사용하지만 물론 자신의 디자인으로 변경할 수 있습니다).

 @if (isset($errors) and count($errors->all()) > 0)
 <div class="alert alert-error">
    <h4 class="alert-heading">Problem!</h4>
     <ul>
        @foreach ($errors->all('<li>:message</li>') as $message)
         {{ $message }}
       @endforeach
    </ul>
</div>

Laravel 4.1에서는 lang 폴더 -> 언어(기본값en) -> validation.php로 쉽게 이동할 수 있습니다.

모델에 이 기능이 있는 경우, 예를 들어 다음과 같습니다.

'group_id' => 'Integer|required',
'adult_id' => 'Integer|required',

또한 오류가 "please enter a group id"가 되지 않도록 하려면 validation.php에 커스텀 배열을 추가하여 "nice" 검증 메시지를 작성합니다.이 예에서는 커스텀 어레이는 다음과 같습니다.

'custom' => array(
    'adult_id' => array(
        'required' => 'Please choose some parents!',
    ),
    'group_id' => array(
        'required' => 'Please choose a group or choose temp!',
    ),
),

다국어 앱에서도 사용할 수 있으므로 올바른 언어 검증 파일을 편집(작성)하기만 하면 됩니다.

app/config/app.compute/app.compute/app.compute/app.compute.compute/app.compute-compute-compute-compute-compute-app.compute-comp은 언제든지 수 .App::setLocale★★★★★★ 。

오류와 언어에 대한 자세한 내용은 검증현지화를 참조하십시오.

라라벨 7에서.

use Illuminate\Support\Facades\Validator;

그런 다음 nice Names를 정의합니다.

$niceNames = array(
   'name' => 'Name',
);

마지막으로 $niceNames를 네 번째 파라미터에 다음과 같이 입력합니다.

$validator = Validator::make($request->all(), $rules, $messages, $niceNames);

커스텀 언어 파일은 다음과 같은 "nice names"의 입력으로 사용합니다.

$validator = Validator::make(Input::all(), $rules);
$customLanguageFile = strtolower(class_basename(get_class($this)));

// translate attributes
if(Lang::has($customLanguageFile)) {
    $validator->setAttributeNames($customLanguageFile);
}
$customAttributes = [
'email' => 'email address',
];

$validator = Validator::make($input, $rules, $messages, $customAttributes);

:attribute는 Atribute 이름(이 경우 first_name)만 사용할 수 있으며 nice 이름은 사용할 수 없습니다.

단, 다음과 같은 메시지를 정의함으로써 각 Atribute+Validation에 대한 커스텀메시지를 정의할 수 있습니다.

$messages = array(
  'first_name_required' => 'Please supply your first name',
  'last_name_required' => 'Please supply your last name',
  'email_required' => 'We need to know your e-mail address!',
  'email_email' => 'Invalid e-mail address!',
);

꽤 오래된 질문이지만 URL에 표시되는 언어의 문제는 다음과 같이 해결할 수 있습니다.

  • 에서 언어와 합니다.config/app.php;
  • 또는 \App:: setLocale($lang)을 설정함으로써

세션 중에 지속할 필요가 있는 경우 현재 "AppServiceProvider"를 사용하여 이 작업을 수행하고 있지만 URL에 의한 언어 변경이 필요한 경우에는 미들웨어가 더 나은 접근법이 될 수 있기 때문에 프로바이더에서는 다음과 같이 하고 있습니다.

    if(!Session::has('locale'))
    {
        $locale = MyLocaleService::whatLocaleShouldIUse();
        Session::put('locale', $locale);
    }

    \App::setLocale(Session::get('locale'));

이렇게 하면 세션이 처리되고 URL에 고정되지 않습니다.

확실히 하자면, 저는 현재 Larabel 5.1+를 사용하고 있습니다만, 4.x와 다른 동작은 아닙니다.

언급URL : https://stackoverflow.com/questions/17047116/laravel-validation-attributes-nice-names

반응형