code

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

codestyles 2020. 10. 9. 11:13
반응형

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


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

나는 이것을 가지고있다:

'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.'
);

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

감사!

편집하다:

문제는 Laravel 프로젝트에 기본 언어를 설정하지 않는다는 것입니다. 언어를 'NL'로 설정하면 위의 코드가 작동합니다. 하지만 내 언어를 설정하면 URL에 언어가 표시됩니다. 그리고 나는 그것을 선호하지 않습니다.

그래서 내 다음 질문 : URL에서 언어를 제거하거나 기본 언어를 설정하여 거기에 나타나지 않게 할 수 있습니까?


네, "좋은 이름"속성은 몇 달 전에 진짜 "문제"였습니다. 이 기능이 이제 구현 되어 사용하기 매우 간단하기를 바랍니다.

간단하게이 문제를 해결하기 위해 두 가지 옵션을 나눌 것입니다.

  1. 전역 아마도 더 널리 퍼져있을 것입니다. 이 방법은 여기에 잘 설명되어 있지만 기본적으로 application / language / XX / validation.php 유효성 검사 파일 을 편집해야 합니다. 여기서 XX는 유효성 검사에 사용할 언어입니다.

    맨 아래에 속성 배열이 표시됩니다. 그것은 당신의 "좋은 이름"속성 배열이 될 것입니다. 귀하의 예를 따르면 최종 결과는 다음과 같습니다.

    '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 에는 많은 언어 패키지가 준비되어 있는 정말 멋진 저장소 가 있습니다. 확실히 당신은 그것을 확인해야합니다.

도움이 되었기를 바랍니다.


이 특정 문제에 대한 정답은 app / lang 폴더 로 이동하여 파일 하단에 속성 이라는 배열이있는 validation.php 파일을 편집하는 것입니다 .

/*
|--------------------------------------------------------------------------
| 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
),

그래서 저는이 배열이 특별히 이러한 속성 이름을 사용자 지정하기 위해 만들어 졌다고 생각합니다.


Laravel 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="">

(validation.php 파일에있는) 배열은

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

나는 똑같은 것을 시도했고 훌륭하게 작동합니다. 도움이 되었기를 바랍니다.

편집하다

또한 나는 당신이 매개 변수를 전달하지 않는다는 것을 알고 $errors->has()있으므로 아마도 그것이 문제 일 것입니다.

다음과 같은 코드가있는 경우 컨트롤러에서이 확인을 수정하려면

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

then you have to pass to the has() method the "register" key (or whatever you are using) like this

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

Another way to display error messages is the following one which I prefer (I use Twitter Bootstrap for the design but of course you can change those with your own design)

 @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>

A late answer but may help someone

In Laravel 4.1 the easy way to do this is go to the lang folder -> your language(default en) -> validation.php

and then for example, when you have in your model

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

And do not want as an error please enter a group id

You can create "nice" validation messages by adding in validation.php to the custom array so in our example, the custom array would look like this

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

This also works with multi-language apps, you just need to edit(create) the correct language validation file.

The default language is stored in the app/config/app.php configuration file, and is english by default. This can be changed at any time using the App::setLocale method.

More info to both errors and languages can be found here validation and localization


The :attribute can only use the attribute name (first_name in your case), not nice names.

But you can define custom messages for each attribute+validation by definine messages like this:

$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!',
);

I use my custom language files as Input for the "nice names" like this:

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

// translate attributes
if(Lang::has($customLanguageFile)) {
    $validator->setAttributeNames($customLanguageFile);
}

Well, it's quite an old question but I few I should point that problem of having the language appearing at the URL can be solved by:

  • Changing the language and fallback_language at config/app.php;
  • or by setting \App::setLocale($lang)

If needed to persist it through session, I currently use the "AppServiceProvider" to do this, but, I think a middleware might be a better approach if changing the language by URL is needed, so, I do like this at my provider:

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

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

This way I handle the session and it don't stick at my url.

To clarify I'm currently using Laravel 5.1+ but shouldn't be a different behavior from 4.x;

참고URL : https://stackoverflow.com/questions/17047116/laravel-validation-attributes-nice-names

반응형