Laravel Validate ->validate() method removed custom added errors?
I'm trying to use the Laravel validator to include some custom error messages before I run the validate() method. However it appears that running this method then removed any previously added errors.
I can confirm that the error message appears when I dump out the validator messages before hitting validate()
$validator = Validator::make(
$this->data,
$this->rules
);
$validator->errors()->add('meal', 'The meal field is required.');
$validator->validate();
How I can validate my data but still include the error relating to the meal?
1 answer
-
answered 2022-05-04 14:36
Jonathan
I believe what you want to use is the after validation hook. This will allow you to add more errors like so:
$validator = Validator::make( $this->data, $this->rules ); $validator->after(function ($validator) { $validator->errors()->add( 'field', 'Something is wrong with this field!' ); }); $validator->validate();
do you know?
how many words do you know
See also questions close to this topic
-
delete a table form a database using laravel command
i need to delete a database table using laravel artisan command . not like this command php artisan migrate:rollback --step=5
i need to create like this route or controller code .
Route::get('/clear/database', function () {
Artisan::call('cache:clear'); return redirect('/');
});
. i also try public function dd()
{ Schema::drop('table_name'); }
but it not working . gives me error like this SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (SQL: drop table
table_name
)no foreign key for the table . what should i do ?
thanks in advance!
-
Foreach for Categories
i have this data, I want to loop with categories for each question. Right now all I can do is loop by displaying sequentially for each question (as in the image).what I want to do is loop and group them based on categories_id , if the categories_id changes it will be given a new line.
// 20220507095412 // http://127.0.0.1:8000/user/exams [ { "id": 16, "ujians_id": 11, "questions_id": 3, "mulai": null, "berakhir": null, "durasi": 60, "isAnswer": 0, "created_at": "2022-05-07T02:53:56.000000Z", "updated_at": "2022-05-07T02:53:56.000000Z", "questions": { "id": 3, "title": "2", "question": "<p>Sarana yang sangat masih dalam menyebabkan oposisi dunia yang sering berdampak pada intervensi asing terhadap Indonesia pada era globalisasi sekarang ini adalah...</p>", "img": null, "categories_id": 1, "created_at": "2022-05-07T02:11:41.000000Z", "updated_at": "2022-05-07T02:11:41.000000Z" } }, { "id": 17, "ujians_id": 11, "questions_id": 1, "mulai": null, "berakhir": null, "durasi": 60, "isAnswer": 0, "created_at": "2022-05-07T02:53:56.000000Z", "updated_at": "2022-05-07T02:53:56.000000Z", "questions": { "id": 1, "title": "13", "question": "<p>Wahidin soedirohoesodo memilik peran penting dalam pergerakan kemerdekaan. Antara lain…22234232</p>", "img": null, "categories_id": 1, "created_at": "2022-05-02T10:39:13.000000Z", "updated_at": "2022-05-03T13:28:24.000000Z" } } ]
@php $no=1 @endphp @foreach($dataUjian as $row) @if($row->isAnswer == 0) <button class="btn btn-primary btn-sm" onclick="getUjian({{$row->questions_id}}, {{$row->id}},{{$row->ujians->users_id}})" >{{$no++}}</button> @else <button class="btn btn-danger btn-sm" disabled>{{$no++}}</button> @endif @endforeach
-
Unit testing with get request
I am trying to create a unit test for one of my api.
In the frontend, I send it this way...
params = { participants: JSON.stringify(participants), section: JSON.stringify(section), }; axios.get('/api/list', params)
while in the controller, it receives the params this way...
public function list(Request $request) { $participants = json_decode($request->participants); $section = json_decode($request->section); }
Now, I tried making a unit test out of this. by doing...
$params = [ 'participants' => ['id', 'name', 'rating'], 'section' => ['id', 'code'], ]; $this->get('/api/list'.http_build_query($params))->assertStatus(200) // $this->json('/api/list', $params)->assertStatus(200) // -> also tried this one // $this->getJson('/api/list', $params)->assertStatus(200) // -> also tried this one // $this->call('GET', '/api/list', $params)->assertStatus(200) // -> also tried this one
But none of them works, it always says
TypeError: json_decode(): Argument #1 ($json) must be of type string, array given
.So, the way I built the url and the params must be all wrong,
so my question here is that, what's the correct way of building the url so that it provides a correct url string format and the controller will json_decode the params?
-
Matching number with regex
Need a single combined regex to match the following logic: The number should be 8 digits long, the 8th digit should be the remainder of (the first 7 digits / 7).
for example: 86008786
remainder = (the first 7 digit)/ 7 = 8600878 / 7 = 6
so the 8 digit 86008786 is valid number.
is it doable with regex?
-
Validation Control are not working on live server [Google Cloud] with VS 2015 (Asp.Net with C#)
On my local machine everything is working fine...but on live server validation control are not working. [I am using Google Cloud (Windows Server 2019)].
I am using VS 2015 (Asp.Net Web Form with c#))
my code is here...
<asp:TextBox ID="txtFirstName" runat="server" placeholder="Your First Name" MaxLength="25" ></asp:TextBox> <asp:RequiredFieldValidator ID="rfvFirstName" runat="server" ControlToValidate="txtFirstName" Display="Dynamic" ErrorMessage="First Name is required." SetFocusOnError="True" ValidationGroup="v" ForeColor="Red"></asp:RequiredFieldValidator> <asp:Button ID="btnSubmit" runat="server" Text="Submit" ValidationGroup="v" />
I read some articles related to this. According to them I added below code in my web.config file but still issue are same...
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" /> <!--Using 4.5 Version only-->
-
Struts2 field validator - Validate multiple fields together
As part of my project I have the credit card month and year as two different fields,
<field name="expiry-month"> <field-validator> ... </field-validator> </field> <field name="expiry-year"> <field-validator> ... </field-validator> </field>
Now, I want to validate the values of these two fields as together so that the credit card expiry month and year are not in past.
How can I do that within XML?
Thank you.
-
ASP.NET MVC and DataTables, cannot redirect to custom error page
I have a problem when combining ASP.NET custom errors and use DataTables in a view.
If DataTables tries to get data from the server and an error occurs, first, the error is caught by ASP.NET MVC in
Application_Error
and from there it is passed to theIndex
action in theErrorController
with the exception information.However, the error page is not displayed, instead the browser jumps to the DataTables error handling in javascript.
I can force the page to be displayed, as in the code below (window.location), but I would like the error page with the original exception to be displayed. If I omit the window.location part, no error page is displayed, even though the
Index
action inErrorController
is triggered.Here is my code:
Global.asax
:protected void Application_Error(object sender, EventArgs e) { Exception exception = Server.GetLastError(); Server.ClearError(); // Redirect to error page var routeData = new RouteData(); routeData.Values.Add("controller", "Error"); if (exception.GetType() == typeof(HttpException)) { // Save error log Log.WriteLog(exception, "", Session["userName"] as string); var code = ((HttpException)exception).GetHttpCode(); if (code == 404) { routeData.Values.Add("action", "NotFound"); } else if (code == 403 || code == 401) { routeData.Values.Add("action", "NotAuthorized"); } else { routeData.Values.Add("action", "BadRequest"); routeData.Values.Add("statusCode", 400); } } else { routeData.Values.Add("action", "Index"); routeData.Values.Add("statusCode", 500); } routeData.Values.Add("exception", exception); // Redirect to error pages Response.TrySkipIisCustomErrors = true; IController controller = new ErrorController(); controller.Execute(new RequestContext(new HttpContextWrapper(Context), routeData)); Response.End(); }
ErrorController
:public ActionResult Index(dynamic exception, int? statusCode = 500) { Response.StatusCode = statusCode.Value; Response.TrySkipIisCustomErrors = true; ViewBag.Message = (exception is String[]) ? exception[0] : exception.Message; return View("Error500"); }
DataTables error handling:
$.fn.dataTable.ext.errMode = 'throw'; $("#tblMSLs").on('error.dt', function (e, settings, techNote, message) { console.log('Error in DataTables tblMSLs: ', message); window.location.href = `${webOrigin}Error?exception=${message}&statusCode=500`; });
-
How to redirect to custom 403 using Middleware - asp.net
I'm trying to redirect if authentication fails to a custom 403 page which Is not working. The web pages should only be accessible if the user is authenticated via LDAP(should belong to a particular group)
this is what i've done so far:
- Added Authorization middleware
- Added Authorization middleware extension
- Configure it in startup.cs
- Added Error controller and Views
public async Task Invoke(HttpContext context) { // create and search ldap DirectoryEntry entry = new DirectoryEntry("LDAP://" + ldapServer); DirectorySearcher mySearcher = new DirectorySearcher(entry); var userName = context.User.Identity.Name; userName = System.IO.Path.GetFileNameWithoutExtension(userName); // look for SAM account names in groups for the user mySearcher.Filter = "(&(objectClass=user)(|(cn=" + userName + ")(sAMAccountName=" + userName + ")))"; SearchResult result = mySearcher.FindOne(); var isAuthorized = false; foreach (string GroupPath in result.Properties["memberOf"]) { if (GroupPath.Contains(AuthorisedGroup)) { isAuthorized = true; } } // Return error if the current user is not authorized if (!isAuthorized) { context.Response.StatusCode = 403; return; } // Jump to the next middleware if the user is authorized await NextRequest.Invoke(context); }
Configure method in startup.cs
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseStatusCodePagesWithReExecute("/Error/{0}"); //app.UseDeveloperExceptionPage(); } else { app.UseStatusCodePagesWithReExecute("/Error/{0}"); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAdAuthorizationMiddleware();//<------- Middleware config app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Fault}/{action=Fault}/{id?}"); }); }
Error Controller
public class ErrorController : Controller { [Route("Error/{statusCode}")] public IActionResult StatusCodeHandler(string statusCode) { return View($"{statusCode}"); } }
I've added 2 views
if I type an invalid url it does show custom 404, but if i set
isAuthorized = false
it doesn't get to the controller hence shows the standard 403 page instead of custom page.Thanks for any help