简体   繁体   中英

Laravel 5.1 How to output HTML in form validation error messages

I have a form request class to validate my data and I am using the messages() method to return custom validation error messages like so:

public function messages()
{
    return [
        'name.valid_name' => 'The name is incorrect, please see the <a href="'.route('naming_conventions').'">Naming Conventions</a> page for instructions on naming.'
    ];
}

So as you can see I want to output a hyperlink in the error message to help the user. When the error message is output though all of the html tags have been converted to entities so that what is actually output is:

The name is incorrect, please see the &lt;a href=&quot;http://local.website.com/naming-conventions&quot;&gt;Naming Conventions&lt;/a&gt; page for instructions on naming.

How can I output HTML in my error message?

Turns out it was the way I was outputting the errors that was causing the HTML entities issue. I was doing the following:

@if (count($errors) > 0)
    <div class="alert alert-danger">
        <strong>Whoops!</strong> There were some problems with your input.<br><br>
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

I had to change <li>{{ $error }}</li> to <li>{!! $error !!}</li> <li>{!! $error !!}</li>

Don't put a hyperlink in the message itself. Try using an @if @endif statement in your view if there are any error messages returned with the response

@if($errors and $errors->has('name.valid_name'))
he name is incorrect, please see the  <a href="">Help link</a>
@endif

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM