Custom Tooltip Plugin
Custom Tooltip plugin is able to create dynamic tooltips for a container.
Version:
1.0
Author:
jakesdavis (Jakes Davis)
Dependency:
jquery-2.1.1.js
Usage
$("#elementID").customTooltip();
$("#elementID").customTooltip({
"position": "n"
});
Parameters
| Name | Type | Description |
|---|---|---|
border |
String | Set border width of tooltip-box |
position |
String | Default position of tooltip wrt container |
events - hover |
Boolean | Set trigger for displaying the tooltip |
events - click |
Boolean | Set trigger for displaying the tooltip |
events - focus |
Boolean | Set trigger for displaying the tooltip |
animate - effect - show |
String | effect to show on display of tooltip |
animate - effect - hide |
String | effect to show on hide of tooltip |
animate - duration |
Integer | Duration of animation effect |
wrapper |
Object | Basic Css Styles for the tooltip wrapper |
content |
Object | Basic Css Styles for the tooltip content area |
arrow |
Object | Basic Css Styles for the tooltip arrow container |
arrow-inner |
Object | Basic Css Styles for the tooltip arrow |
border
Set border width of tooltip-box
Default Value : 1px
Expected Value: 1px, 2px, etc
position
default position of tooltip wrt container
Default Value : n
Expected Value: n|e|w|s|nw|ne|sw|se|g
events - hover
Set trigger for displaying the tooltip
Default Value : true
Expected Value: true|false
events - click
Set trigger for displaying the tooltip
Default Value : false
Expected Value: true|false
events - focus
Set trigger for displaying the tooltip
Default Value : false
Expected Value: true|false
animate - effect - show
Default Value : fade
Expected Value: fade
animate - effect - hide
Default Value : fade
Expected Value: fade
animate - duration
Default Value : 500
Expected Value: Integer
wrapper
Basic Css Styles for the tooltip wrapper
content
Basic Css Styles for the tooltip wrapper
arrow
Basic Css Styles for the tooltip wrapper
arrow-inner
Basic Css Styles for the tooltip wrapper
Browser Support
Chrome, Mozilla firefox
License
The MIT License (MIT)
Copyright (c) 2015 jakesdavis
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


Header file for including functions required to find the segments for given set of input points.
More...
#include <vector>
#include "line.hpp"
Go to the source code of this file.
|
| vector< Point > | slice (int i, int j, vector< Point > P) |
| | Slices out indices from i to j from the vector of points P. More...
|
| |
| double | cal_err (vector< Point > P) |
| | Gives the cumulative error of the calculated line for the given point set, Line is calculated by the normal formula. More...
|
| |
| void | OPT (int j, double cost, vector< double > &M, vector< vector< double >> Err) |
| | It is the recursive function which calculates the penalty at each index. More...
|
| |
| void | Segmented_Least_Square (vector< Point > P, double cost, vector< double > &M, vector< vector< double >> &Err) |
| | Driver function for OPT and also calculates error for all possible (start, end) pairs. More...
|
| |
| void | Find_Segment (int j, vector< Point > P, vector< double > M, double cost, vector< vector< double >> Err, vector< vector< Point >> &result) |
| | recursively finds the best possible partitions of points, given M penalty at each index, P input point set, Err error for all possible segments of points More...
|
| |
Header file for including functions required to find the segments for given set of input points.
- Authors
- Kumar Pranjal 2018A7PS0163H
-
Ashna Swaika 2018A7PS0027H
-
Abhishek Bapna 2018A7PS0184H
-
Ashish Verma 2018A7PS0009H
◆ cal_err()
| double cal_err |
( |
vector< Point > |
P | ) |
|
Gives the cumulative error of the calculated line for the given point set, Line is calculated by the normal formula.
- Parameters
-
- Returns
- error
◆ Find_Segment()
| void Find_Segment |
( |
int |
j, |
|
|
vector< Point > |
P, |
|
|
vector< double > |
M, |
|
|
double |
cost, |
|
|
vector< vector< double >> |
Err, |
|
|
vector< vector< Point >> & |
result |
|
) |
| |
recursively finds the best possible partitions of points, given M penalty at each index, P input point set, Err error for all possible segments of points
- Parameters
-
| [in] | j | integer, partitions have to be found for elements lying before this index |
| [in] | P | vector of points, given input |
| [in] | M | vector of double, stores the penalty of every index |
| [in] | cost | double, constant cost |
| [in] | Err | vector of vector of double, stores the error values corresponding to every ( i, j ) pairs |
| [out] | result | vector of vector of points, gives the final optimal partitions for the set of points |
- Note
- result gives a vector of partitions where each partition is a vector of points belonging to the same partition.
◆ OPT()
| void OPT |
( |
int |
j, |
|
|
double |
cost, |
|
|
vector< double > & |
M, |
|
|
vector< vector< double >> |
Err |
|
) |
| |
It is the recursive function which calculates the penalty at each index.
- Parameters
-
| [in] | j | integer, gives the index for which we wish to find penalty |
| [in] | cost | integer constant |
| [out] | M | vector of double which calculates minimum penalty at any given index |
| [in] | Err | vector of vector of double, gives the error for different segments |
- Note
- M is given as the output, that is, it is calculated for index j
◆ Segmented_Least_Square()
| void Segmented_Least_Square |
( |
vector< Point > |
P, |
|
|
double |
cost, |
|
|
vector< double > & |
M, |
|
|
vector< vector< double >> & |
Err |
|
) |
| |
Driver function for OPT and also calculates error for all possible (start, end) pairs.
- Parameters
-
| [in] | P | vector of points, given input |
| [in] | cost | double, constant cost |
| [out] | M | vector of double, stores the penalty of every index |
| [out] | Err | vector of vector of double, stores the error values corresponding to every ( i, j ) pairs |
- Note
- M and Err are the outputs for the functions. Err[i][j] for any given i and j refers to the error a segment starting from point on i-th index upto point on (i+j+1)-th index gets.
◆ slice()
| vector<Point> slice |
( |
int |
i, |
|
|
int |
j, |
|
|
vector< Point > |
P |
|
) |
| |
Slices out indices from i to j from the vector of points P.
- Parameters
-
| [in] | i | integer, starting index |
| [in] | j | integer, ending index |
| [in] | P | vector of points, the array from where i to j elements will be sliced from |
- Returns
- result vector of points, the sliced out vector of points
- Note
- the original vector P remains unchanged during this process


Easy Classes
Home
Services
About Us
Contact
Courses
Explore Most Demanding Languages!!!
Learn c++ with our best instructors.
Learn Java with our best instructors.
Learn HTML with our best instructors.
Learn Python with our instructors.
Learn PHP with our best instructors.
© 2019 EasyLearn Inc. All rights reserved.


|
||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | |||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |
java.lang.Object | +--net.sf.saxon.trans.KeyManager
KeyManager manages the set of key definitions in a stylesheet, and the indexes associated with these key definitions. It handles xsl:sort-key as well as xsl:key definitions.
The memory management in this class is subtle, with extensive use of weak references. The idea is that an index should continue to exist in memory so long as both the compiled stylesheet and the source document exist in memory: if either is removed, the index should go too. The document itself holds no reference to the index. The compiled stylesheet (which owns the KeyManager) holds a weak reference to the index. The index, of course, holds strong references to the nodes in the document. The Controller holds a strong reference to the list of indexes used for each document, so that indexes remain in memory for the duration of a transformation even if the documents themselves are garbage collected.
Potentially there is a need for more than one index for a given key name, depending on the primitive type of the value provided to the key() function. An index is built corresponding to the type of the requested value; if subsequently the key() function is called with the same name and a different type of value, then a new index is built.
| Constructor Summary | |
KeyManager(Configuration config)
create a KeyManager and initialise variables |
| Method Summary | |
java.util.List |
getKeyDefinitions(int fingerprint)
Get all the key definitions that match a particular fingerprint |
SequenceIterator |
selectByKey(int fingerprint,
DocumentInfo doc,
AtomicValue value,
Controller controller)
Get the nodes with a given key value |
void |
setKeyDefinition(int fingerprint,
KeyDefinition keydef)
Register a key definition. |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Constructor Detail |
public KeyManager(Configuration config)
| Method Detail |
public void setKeyDefinition(int fingerprint, KeyDefinition keydef) throws javax.xml.transform.TransformerConfigurationException
fingerprint
- Integer representing the name of the keykeydef
- The details of the key's definition
javax.xml.transform.TransformerConfigurationException
public java.util.List getKeyDefinitions(int fingerprint)
fingerprint
- The fingerprint of the name of the required key
public SequenceIterator selectByKey(int fingerprint, DocumentInfo doc, AtomicValue value, Controller controller) throws XPathException
fingerprint
- The fingerprint of the name of the required keydoc
- The source document in questionvalue
- The required key valuecontroller
- The controller, needed only the first time when the key is being built
XPathException
|
||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | |||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |


library(tidyverse)
library(cowplot)
library(broom)
library(modelr)
library(viridis)
library(lubridate)
library(knitr)
#knitr::opts_knit$set(root.dir = '/Users/scottsaunders/git/labwork/IDA/12_10_18')
knitr::opts_chunk$set(tidy.opts=list(width.cutoff=60),tidy=TRUE, echo = TRUE, message=FALSE, warning=FALSE, fig.align="center")
theme_1 <- function () {
theme_classic() %+replace%
theme(
axis.text = element_text( size=12),
axis.title=element_text(size=14),
strip.text = element_text(size = 14),
strip.background = element_rect(color='white'),
legend.title=element_text(size=14),
legend.text=element_text(size=12),
legend.text.align=0,
panel.grid.major = element_line(color='grey',size=0.1)
)
}
theme_set(theme_1())
#source("../../tools/echem_processing_tools.R")
Notebooks that used Version 2 analysis:
The next approach I took to measuring \(D_{ap}\) was to soak \(\Delta phz\) biofilms with PYO in one reactor and then transfer the biofilms to a second reactor with fresh medium. The echem measurements were then taken in the “transfer” reactor, so that we could be more confident the signal was coming from biofilm associated PYO, not the solution PYO.
In order to do this, I needed a way to estimate the concentration of PYO left in the biofilm when making the measurements. What we settled on is to take a single electrode square wave voltammetry (SWV) scan after taking each generator collector (GC) scan. What we realized was that plotting \(I_{gc}\) vs. \(I_{swv}\) actually yielded a line that depends on \(D_{ap}\), which was what we sought in V1 for the \(I_{gc}\) vs. \(C\) plots.
\(I_{gc}\) and \(I_{swv}\) depend on \(D_{ap}\) differently, because the currents arise through different processes. \(I_{gc}\) is an equilibrium flux that depends on a diffusion coefficient and concentration gradient similar to fick’s law. \(I_{swv}\) depends on non equilibrium diffusion (fick’s second law) as described by the cottrell equation - while the electrode is poised it constantly changes the concentration gradient.
Slope of the linear fit of GC vs. SWV titration plot: \[slope = m = \frac{\Delta I_{gc}}{\Delta I_{swv}} \tag{eq. 1}\] Generator collector peak current: \[I_{gc} = nFSCD_{ap} \tag{eq. 2}\]
Square Wave peak current: \[I_{swv} = \frac{nFACD_{ap}^{1/2}}{\pi^{1/2}t_p^{1/2}} \psi \tag{eq. 3}\] Substituting into eq. 1: \[m = \frac{I_{gc}}{I_{swv}} = \frac{nFSCD_{ap}}{\frac{nFACD_{ap}^{1/2}}{\pi^{1/2}t_p^{1/2}} \psi} \tag{eq. 4}\] Assuming that \(D_{ap}\) and \(C\) are the same for GC and SWV we can simplify: \[m = \frac{S\pi^{1/2}t_p^{1/2}D_{ap}^{1/2}}{A\psi} \tag{eq. 5}\]
Rearranged for \(D_{ap}\): \[D_{ap} = \frac{m^2 A^2 \psi^2}{S^2\pi t_p} \tag{eq. 7}\]
Therefore, with this dataset in hand, we should be able to estimate \(D_{ap}\) for the biofilm associated PYO, by measuring in the transfer reactor.
In V1, we were already using a titration approach to vary \(C\), so we continued this approach by soaking the \(\Delta phz\) biofilm in increasing concentrations of synthetic PYO. After each soak, I briefly washed the biofilm and then transferred it to another reactor with fresh medium.
We had reasonably decided to take measurements at a timepoint where the system had reached equilibrium. For various reasons, we assumed that at equilibrium we would only be measuring PYO stably associated with the biofilm, and that the solution concentration was negligible. Two reasons we made these assumptions were that we could transfer the biofilm repeatedly into fresh solution and always detect PYO signal and that measurements on the LC-MS suggested that the solution concentration of PYO was in the nM range, which I thought was below the detection limit of the electrode.
I implemented this protocol by taking successive SWV scans as the biofilm equilibrated in the transfer reactor over the course of ~1 hour. Once the peak SWV current stopped noticeably decreasing, I took a GC and SWV scan. Then I soaked the biofilm in the next higher PYO concentration and repeated for 5-7 concentrations total.
Note that this was quite a long experiment with few datapoints, since each equilibrium datapoint took at least 1.5 hrs and required a potentiostat to monitor the reactor during the entire process.
In general, V2 titrations looked linear. That said the slope of these \(I_{gc}\) vs. \(I_{swv}\) plots was significantly less for the transfer measurements than measurements taken in the soak reactor (with a biofilm or blank IDA).
gc_swv_equil <- read_csv("../12_04_18_psoralen_biofilm/Processing/12_04_18_processed_gc_swv_equil.csv")
ggplot(gc_swv_equil %>% filter(segment == "1" & condition ==
"control"), aes(x = signal_from_swv, y = signal_from_gc)) +
geom_point() + geom_line()
After doing these experiments for a while thinking things were fine, I finally decided to explicitly measure background signal in the transfer reactor (Lenny had suggested this long ago). Below is a plot of the transfer reactor measured “at equilibrium” after an hour with a biofilm coated IDA, followed by a blank IDA.
blank_GC_scans <- read_csv("../12_04_18_psoralen_biofilm/Processing/12_04_18_processed_blank_GC_scans.csv")
ggplot(blank_GC_scans %>% filter(E < 0 & condition == "control"),
aes(x = E, y = current, color = blank)) + geom_path(size = 1) +
facet_wrap(~PHZadded, scales = "free") + ylim(0, 1.5e-08) +
scale_x_reverse()
It is clear that the amount of background signal from PYO in solution is significant in these measurements. It is unclear if all of the observed biofilm signal is due to the solution or not. One approach might be to try to background subtract the signal from the blank electrode from the biofilm electrode, however, this assumes \(I_{gc} = I_{biofilm} + I_{blank}\). We know that this is not true in the soak phase, because the biofilm electrode actually shows less signal than the blank electrode. Therefore any attempt to background subtract would get impractically complicated (you probably need to know fraction of electrode exposed to solution, \(D_{ap}\) for each phase, and concentrations).


Moogle
问题描述 :
You got the original idea of making map software, called Moogle Maps, for the new cool Maple mPhone. It will even be capable of indicating the location of a house address like ”Main Street 13”. However, since the mPhone has limited storage capacity, you need to reduce the data amount. You don’t want to store the exact location of every single house number. Instead only a subset of the house numbers will be stored exactly, and the others will be linearly interpolated.
So you want to select house numbers that will minimise the average interpolation error, given how many house locations you have capacity to store. We view the street as a straight line, and you will always store the first and the last house location.
Given that you’ve stored the locations xi and xj for the houses with numbers i and j respectively, but no other house in between, the interpolated value for a house with number k with i < k < j is xi + (xj – xi) * (k-i)/(j-i).
So you want to select house numbers that will minimise the average interpolation error, given how many house locations you have capacity to store. We view the street as a straight line, and you will always store the first and the last house location.
Given that you’ve stored the locations xi and xj for the houses with numbers i and j respectively, but no other house in between, the interpolated value for a house with number k with i < k < j is xi + (xj – xi) * (k-i)/(j-i).
输入:
The first line of input gives a single integer, 1 <= t <= 50, the number of test cases.
For each test case, there are two lines. The first contains 2 <= h <= 200 and 2 <= c <= h, where h is the number of houses in the street and c is the number of house locations that can be stored. The second contains h integers in increasing order giving the location of the h houses. Each location is in the interval [0, 1000000].
For each test case, there are two lines. The first contains 2 <= h <= 200 and 2 <= c <= h, where h is the number of houses in the street and c is the number of house locations that can be stored. The second contains h integers in increasing order giving the location of the h houses. Each location is in the interval [0, 1000000].
输出:
For each test case, output the average interpolation error over all the h houses for the optimal selection of c house locations to store. The output should be given with four decimal places, but we will accept inaccuracies of up to ±0.001.
样例输入:
2 4 3 0 9 20 40 10 4 0 10 19 30 40 90 140 190 202 210
样例输出:
0.2500 0.3000
(adsbygoogle = window.adsbygoogle || []).push({});
文章写得挺好，就是最后的斐波那契那个没有看明白
输出规范写错了哦~
使用代码高亮的插件，再修改下css
第二个方法挺不错。NewHead代表新的头节点，通过递归找到最后一个节点之后，就把这个节点赋给NewHead，然后一直返回返回，中途这个值是没有变化的，一边返回一边把相应的指针方向颠倒，最后结束时返回新的头节点到主函数。
没有对题目进行一番分析，真是美中不足啊
这个问题别太纠结了，不同的编译器结果不一
注释很详细，多谢分享！
a是根先忽略掉，递归子树。剩下前缀bejkcfghid和后缀jkebfghicd，分拆的原则的是每个子树前缀和后缀的节点个数是一样的，根节点出现在前缀的第一个，后缀的最后一个。根节点b出现后缀的第四个位置，则第一部分为四个节点，前缀bejk，后缀jkeb，剩下的c出现在后缀的倒数第2个，就划分为cfghi和 fghic，第3部分就为c、c


When you help others make better choices, be appreciated for it
Prison Officers. You at your best
Working in a prison is no ordinary job. But if you have what it takes, it could be a very rewarding career. To begin with - depending on your contracted hours – prison officer jobs attract potential starting salaries of up to £30,000 in London, £27,688 in the South East, and £23,052 in most other locations. (See FAQs for details.) In addition, you’ll receive a number of benefits including a pension and the ability to earn through overtime.
Here, you’ll discover more about our recruitment process. It’ll tell you what we look for in our prison officers, as well as help you understand what you’ll do and what you’ll gain from the role.
What is HM Prison & Probation Service?
Created in April 2017, Her Majesty's Prison and Probation Service (HMPPS) is a new agency in the Ministry of Justice, covering 121 prisons and employing over 42,000 staff. Our mission: to drive the biggest reform of our prison system in a generation. Across the UK, we're committed to improving how we rehabilitate offenders and protect the public.
We want to build real pride in the prison service and make it a place where ambitious professionals thrive. By applying to a local prison, you'll become part of a major organisation that invests in people. And for our prison officers, that means creating opportunities for higher pay, recognition and development through our promotion, leadership and apprenticeship programmes.
The role
As a prison officer, your career can take you in many different directions. Developing your skills from day one, the chances to move into new areas will always be there. You could be on a residential wing, in reception, in the segregation unit, working with vulnerable prisoners, with mothers and babies, or on the healthcare unit.


internal val startKeys: ConcurrentLinkedQueue<String>
A queue of Request Keys used for providing the right response key.
startKeys - A queue of Request Keys used for providing the right response key.
startKeys


Address based search examples/ideas/issues
Results
FPI currently a result per title1 (tenure), showing the A1 Property description - and the property description is the link.
Moving to a results per address, with all the tenures for that address grouped to that result, and displaying the postal address not the property description
1: So is Find a Property - in both services people pick/buy the wrong record becasue of this
A result per title (tenure), showing the A1 address, (current FPI), means for the user:
- the address does not match their mental model of postcodes and addresses
- more results for the user to deal with
- people pick / buy the wrong document
- less properties/titles can be found - hits the license limit more frequently.
A result per postal address, showing the postal address, means for the user:
- matches the postcode model
- help people understand that it's not one title record per property - that they will have to make a further choice
- more properties and titles can be found - in total, and - found first time
example set of results
No hyperlinks, and not sure if all these titles would be related to a postal address
Shows things/complexity about the order - is in alpha-numeric order (assuming that 6 Mandela can be identified numerically between 5 and 7)
-
5 Mandela Way, Southampton, SO15 5RZ
Freehold -
Flat 1, 6 Mandela Way, Southampton, SO15 5RZ
-
Freehold
-
Leasehold
-
-
Flat 2, 6 Mandela Way, Southampton, SO15 5RZ
-
Freehold
-
Leasehold
-
-
7 Mandela Way, Southampton, SO15 5RZ
Freehold -
8 Mandela Way, Southampton, SO15 5RZ
-
Freehold
-
Leasehold
-
Leasehold
-
Leasehold
-
-
"Church house", Mandela Way, Southampton, (SO15 5RZ)
Freehold -
blair court, Mandela Way, Southampton, (SO15 5RZ)
Freehold -
the former sites of 24-44 Mandela Way, Southampton, (SO15 5RZ)
Freehold -
Blair gardens, blair court, Mandela Way, Southampton, (SO15 5RZ)
Freehold
linking to page per title (tenure) - What FPI and FaP do
Keeping existing page per title (tenure) - means the link must be on the tenure
User problems - what are freehold and leasehold? which link do i need? Why does 'page per title' show a different address?
Try No 6, Flats 1 and 2, Freehold
-
5 Mandela Way, Southampton, SO15 5RZ
-
6 Mandela Way, Southampton, SO15 5RZ
-
Flat 1, 6 Mandela Way, Southampton, SO15 5RZ
-
Flat 2, 6 Mandela Way, Southampton, SO15 5RZ
-
7 Mandela Way, Southampton, SO15 5RZ
-
8 Mandela Way, Southampton, SO15 5RZ
-
"Church house", Mandela Way, Southampton, (SO15 5RZ)
-
babbage court, Mandela Way, Southampton, (SO15 5RZ)
linking to page per property - option 1
matches user mental model - how they are searching / the results...
New Page - page per property which helps the user to pick the right title (tenure) - which breaks the problem down for the user, and then links onward to page per title
Try Flat 1, 6 Mandela Way
Or - page per property replaces page per title - which breaks the problem down for the user, and then links onward buy it
Try Flat 2, 6 Mandela Way
-
5 Mandela Way, Southampton, SO15 5RZ
1 freehold property record -
Flat 1, 6 Mandela Way, Southampton, SO15 5RZ
-
1 Freehold and 1 leasehold property records
-
-
Flat 2, 6 Mandela Way, Southampton, SO15 5RZ
-
1 freehold and 1 leashold property records
-
-
7 Mandela Way, Southampton, SO15 5RZ
1 freehold property record -
8 Mandela Way, Southampton, SO15 5RZ
-
1 freehold and 3 leasehold property records
-
-
Plaza Hotel, Mandela Way, Southampton, (SO15 5RZ)
1 freehold and 499 leasehold property records
linking to page per property - option 2
matches user mental model - how they are searching / the results...
New Page - page per property which helps the user to pick the right title (tenure) - which breaks the problem down for the user, and then links onward to page per title
Try Flat 1, 6 Mandela Way
Or - page per property replaces page per title - which breaks the problem down for the user, and then links onward buy it
Try Flat 2, 6 Mandela Way


EXCLUSIVE: Omarion Breaks His Silence on Lil Fizz & Apryl Jones Relationship
by VladTVIn this clip, Omarion broke his silence on the Apryl and Fizz situation. Omarion said that he doesn't really feel any type of way about their relationship, he'd just prefer to be left out of the "narrative."


Tourney Homebrew Hearthstone Tournament
This text is displayed if your browser does not support HTML5 Canvas.
Clear
Draw
Nothing yet
Copyright © 2015 Aris Papaiakovou


WEEK 7 THURSDAY
Year 1 (Year 2)
FIRST READING Sirach 5:1-8
A reading from the Book of Sirach
Do not set your heart on your wealth, nor say,
"I have enough." Do not follow your inclination and strength, walking
according to the desires of your heart. Do not say, "Who will have power
over me?" or “Who will bring me down because of my deeds?” for God will
surely punish you. Do not say, "I sinned, and what happened to me?"
for the Most High is slow to anger. Do not be so confident of atonement that
you add sin to sin. Do not say, "His mercy is great, he will forgive the
multitude of my sins," for both mercy and wrath are with him, and his anger
rests on sinners. Do not delay to turn to the Lord, nor postpone it from day to
day; for suddenly the wrath of the Lord will go forth, and at the time of
punishment you will perish. Do not depend on dishonest wealth, for it will not
benefit you in the day of calamity.
The word of the Lord
RESPONSORIAL PSALM Psalm 1:1-2.3.4 and 6 (R. Psalm 40:5ab)
R. Blessed the man who has placed his trust in the Lord.
Blessed indeed is the man who follows not the
counsel of the wicked, nor stands in the path with sinners, nor abides in the
company of scorners, but whose delight is the law of the LORD, and who ponders
his law day and night.
R. Blessed the man who has placed his trust in the
Lord.
He is like a tree that is planted beside the
flowing waters, that yields its fruit in due season, and whose leaves shall
never fade; and all that he does shall prosper.
R. Blessed the man who has placed his trust in the
Lord.
Not so are the wicked, not so! For they, like
winnowed chaff, shall be driven away by the wind. For the LORD knows the way of
the just, but the way of the wicked will perish.
R. Blessed the man who has placed his trust in the
Lord.
FIRST READING James 5:1-6
A reading from the Letter of Saint James
Come now, you rich, weep and howl for the miseries
that are coming upon you. Your riches have rotted and your garments are
moth-eaten.  You have laid up treasure for
the last days. Behold, the wages of the labourers who mowed your fields, which
you kept back by fraud, cry out; and the cries of the harvesters have reached
the ears of the Lord of hosts. You have lived on the earth in luxury and in
pleasure; you have fattened your hearts in a day of slaughter.
The word of the Lord
RESPONSORIAL PSALM Psalm 49:14-15c.15d-16.17-18.19-20 (R. Matthew 5:3)
R. Blessed are the poor in spirit, for theirs is the kingdom of heaven.
This is the way of the foolish, the outcome of
those pleased with their lot: like sheep they are driven to the grave, where
death shall become their shepherd, and the upright shall have dominion.
R. Blessed are the poor in spirit, for theirs is the
kingdom of heaven.
Their outward show wastes away with the morning, and the grave becomes their home. But God will
ransom my soul from the grasp of hell; for he indeed will receive me.
R. Blessed are the poor in spirit, for theirs is the
kingdom of heaven.
Then do not fear when a man grows rich, when the
glory of his house increases. He takes nothing with him when he dies, his glory does not follow him below.
R. Blessed are the poor in spirit, for theirs is the
kingdom of heaven.
Though he flattered himself while he lived, 'People
will praise me for all my success,' yet he will go to join his forebears, and
will never see the light any more.
R. Blessed are the poor in spirit, for theirs is the
kingdom of heaven.
R. Alleluia. Accept the word of God, not as the word of men, but as what it really is, the word of God. R. Alleluia.
GOSPEL Mark 9:41-50
A reading from the holy Gospel according to Mark
At that time: Jesus said to his disciples, “Whoever
gives you a cup of water to drink because you bear the name of Christ, will by
no means lose his reward. "Whoever causes one of
these little ones who believe in me to sin, it would be better for him if a
great millstone were hung round his neck and he were thrown into the sea.   And if your eye causes you to sin, pluck
it out; it is better for you to enter the
The Gospel of the Lord.


AccorTrackingDecorator test
Autodecorated links
all.accor.com, merchantid will be Overwritten
Hash test


CRITICALSTART
Loading...
Feedback
Loading...
Loading...
RSA Security Analytics Configuration
Loading...
Manage Pivot Queries
Loading...
NetWitness Investigator Configuration
Loading...
Manage Pivot Queries
Loading...
Carbon Black Configuration
Loading...
Manage Pivot Queries
Loading...
Loading...


Fri 13 July 2018
By Rob Spaul
In Research .
As I have become more interested in actuarial research (mainly GI/P&C) I have realised that beyond web search I didn't really know where to look. After a bit of research I have collected the following sources.
My general impression is that collation of actuarial research is in a poor state. While there is a lot of interesting research and dedicated people furthering the profession, the research is not as accessible as it should be. A lot of my criticisms are probably echoed in other disciplines but measured against the 'ideal' things could be much better.
Far to much research does not make it into a journal or other well cataloged resource (e.g. papers for GIRO) making them hard find. I single out the IFoA website for particular criticism as finding GIRO papers is far too difficult (try finding papers from the most recent GIRO conference). The CAS website is well laid out in comparison.
Perhaps I should not have skipped the Introduction to the Library talk when I started university but to get access to journals such as BAJ or ASS is very difficult. The IFoA provides a means to access the journals (more below) but even that is hard to find.
A lot of papers lack the basics such as the paper's date and the forum in which it was made available, particularly for older papers. Even some fairly recent papers are poor quality scans.
If papers and presentations are made available on the web the URLs can change. A lot of scientific literature has adopted DOI's to enable a reliable way of linking to research but this has not been adopted by CAS or IFoA for non-journal material.
In 2018, why are we still sharing research by PDF? There has been a lot of talk about this across the scientific community as this Atlantic article summarises well. Markus Gesmann's blog is a great example of how research can be made more useful combining his thoughts with the code, data and hyperlinks to the references he has used - so much more useful than a PDF.
Journals
IFoA's Library Services
General link
Direct link to page for accessing journals such as BAJ and AAS (IFoA members only)
The University of Iowa's list
The university maintain a list of actuarial and insurance journals although some of the links don't work.
Database of Actuarial Research Enquiry (DARE)
CAS maintain a catalog of actuarial research.
Although not complete, potentially useful. Not clear how frequently it is updated and no DOI information.
British Actuarial Journal (BAJ)
Accessed via IFoA library services (see link).
ASTIN Bulletin
IAA website
When accessing via IAA link all the articles are available to read and download.
Annals of Actuarial Science (AAS)
Accessed via IFoA library services (see section).
Variance
Published, peer reviewed journal of the Casualty Actuarial Society.
Available online without restriction
Doesn't seem to be carried by journal portals and no DOI information.
CAS E-Forum
non-refereed publications
https://www.casact.org/pubs/forum/
Conferences
ICA - International Conference for Actuarial Science
ICA 2018
RPM
GIRO
CRLS
Data Science in Insurance


After talking about one of the most popular scheduling algorithms used by operating systems to schedule processes, let’s implement it! This will be an implementation that simulates an actual multi-level feedback queue processing blocking and non-blocking processes with multiple priority levels.
One of the main jobs of operating system kernels is that they need to be able to execute all of the processes running on your computer efficiently such that high priority processes are completed as quickly as possible, while also ensuring that there is some fairness in how they schedule processes; even if a process is a low priority, it eventually needs to complete execution.
In order to achieve this, a scheduler looks through the queues for the highest priority process and then executes it for a time quantum (a slice of time), which has been allocated to that queue by the processor. Once the time quantum is up, the process has either completed or it hasn’t. If it hasn’t, then the process is shunted to the next lower priority queue to wait for its turn again. If the process completed during the initial time quantum, then it gets discarded and the scheduler moves on to the next process in line. Queues are processed in first-in-first-out (FIFO) order.
The time quantum is further divided into smaller amounts of time called
work time
.  If the process has not
finished, and has not become a blocking process, then it will be processed
again for the work time. The same process is repeatedly allowed to work
until the full quantum time has been reached, or it finishes, at which
point, if the process has not finished, it will be sent to the next
lower-priority queue, or if already in the lowest priority queue, sent to
the back of the line in that queue.
One thing to note is that processes in higher priority queues are allocated less CPU time than processes in a lower priority queue. The logic here is that the scheduler wants to get through as many of the short, high priority processes first, then the long, high priority processes, followed by the short low priority processes, before finally getting around to the long, low priority processes. Oftentimes, these long-running low priority processes only get allocated CPU time when your computer is idle, because during high usage periods, new processes are constantly being added to the highest-priority queue by the scheduler.
Nothing special here. Just run npm install
in the root
directory, then start working on your implementation, using the provided
skeleton code and comments for guidance / pointers. Run
npm test
when you want to check your code against the test
suite, or npm test:watch
if you’d like to keep the tests
running as you work. You can also do
npm run test <name-of-test-suite>
to run one suite out
of the three.
Our MLFQ implementation will be comprised of two types of queues: blocking queues and CPU queues. There will be one blocking queue and three CPU queues in our implementation. The blocking queue is where blocking processes go; all other processes go into the CPU queues. Each queue will have a different priority level, with a different time quantum allocation (which designates how much time each process in the associated queue receives from the CPU).
The blocking queue will have the highest priority (since we want to get
through blocking processes as soon as possible), followed by the three CPU
queues. You’ll be implementing three classes, a Process class to represent
blocking and non-blocking processes, a Queue class to represent the
different types of queues, and a Scheduler class to represent the
scheduler itself. Then, inside main.js
is where these classes
will be executed to simulate a scheduler working through processes.
Another important aspect that should be touched on is how queues, processes, and the scheduler all communicate with each other. For example, a process may need to let the scheduler and its parent queue know that the process has started a blocking operation, and thus needs to be moved to the blocking queue. Or conversely, a blocking process will need to notify the scheduler and its queue that it has finished its blocking operation, and can thus be moved to a CPU queue. The classes handle this communication by emitting interrupts at the appropriate times.
The pseudo code for our MLFQ implementation is as follows:
Loop:
If a process exists in the blocking queue:
Work on removing each process in the blocking queue on a First In First Out (FIFO) basis
Do blocking work for the amount of time specified for the current iteration
When a process completes its blocking operation, emit an interrupt to the scheduler
The scheduler removes the process from the blocking queue and
adds it to the highest priority level CPU queue
Beginning with the top priority CPU queue, look through each queue for a process to run; processes should be processed in FIFO order
If a process is found:
Do non-blocking work for the amount of time specified for the current iteration
If the process becomes blocking:
Emit an interrupt to the scheduler notifying it that the process has become blocking
The scheduler removes the now-blocking process from the CPU queue
Places it on the blocking queue
Restarts the time quantum with the next process in the CPU queue
If the end of the time quantum has been reached:
Remove the process that is currently being worked on from the top of the CPU queue
If the process is not finished:
If the process is already in the lowest priority queue:
Add it to the back of the same queue
Else:
Add the process to the back of the next lower priority queue
Break out of the current iteration and continue looping
If no processes are found in any queues, the scheduler can idle while waiting for new processes
(in our case, the program will be done)
Implement priority boosting within your MLFQ. Priority boosting is the idea that there is a global time quantum of, say, 500 ms that elapses. Once that global time quantum hits 0, it should reset, and every process in any of the available queues should all be moved back up to the top-level priority queue. This is one such scheme that is used in order to ensure that the bottom-of-the-barrel processes receive some additional attention.
Think about how this feature should be incorporated into your current MLFQ implementation. Which component of the MLFQ should be responsible for the global time quantum? How should processes be notified that they’re recieving a priority boost, and how should that be facillitated?
Here’s a chapter from an operating systems textbook that dives a lot deeper into the theory and motivation behind the multi-level feedback queue: http://pages.cs.wisc.edu/~remzi/OSTEP/cpu-sched-mlfq.pdf
Also this link to some dude’s copious notes on the topic of process scheduling on Unix kernels: https://notes.shichao.io/lkd/ch4/


Properties can be viewed by double-clicking on component or selecting 'Properties' option from component
right-click option list. The properties contain a 'General' tab. Common and mandatory properties are present in the General tab.
- Name - The Name field will specify the name of the component as desired by the user.
- ID - ID field will specify unique id for every component.
- Type - Type further categorizes the component to detailed operation that it intends to perform. Here it is of type command FTP.
- Protocol - Provides drop-down to select the appropriate file transfer protocol from available list like FTP, SFTP, AWS S3 HTTPS.
- Host - Required to specify IP address or host name of server. Required property, if user opts for FTP or SFTP protocol.
- Port - Port simply accepts a numeric number starting from 0 to maximum 65535. Required property, if user opts for FTP or SFTP protocol.
- Authentication - User needs to provide connection details to establish the connection with appropriate server. Authentication editor displays different
modes of authentication based on protocol selection.
For FTP protocol, authentication editor provides 'Standard Authentication' mode, which contains textbox to accept User ID and Password.
For SFTP protocol, authentication editor provides two i.e. 'Standard Authentication' and 'User ID and Key' authentication mode.
In case of 'User ID and Key' authentication mode, user needs to specify the User ID and Private Key to create a connection.
For AWS S3 HTTPS protocol, authentication editor provides two i.e. 'AWS S3 Access Key' and 'AWS S3 Property File' authentication configuration mode.
- Connection Time-Out - It defines the connection time out in milliseconds.
- Number of Retries - It defines the number of tries to establish the connection.
- Operation Configuration - User can use Operation Config to provide the operation details.
- Operation - Provides options to select the required file transfer operation -
Get Files - Required to download the file from remote location to local path.
Put Files - Required to upload the file from local to remote path.
Write Mode - Write Mode provides two options i.e. 'Overwrite If Exists' and 'Fail If Exists'. User can select 'Overwrite If Exists' option to overwrite the file at the time of Get Files operation, if exists. On the other side, user can opt for 'Fail If Exists' option to fail the operation in case same file is already available at given local path.
User need to specify following values to Get or Put Files From/To AWS S3.
S3 Bucket - Specifies AWS S3 bucket name
S3 File Path - Specifies AWS S3 file path for operation
AWS Region - Specifies AWS S3 region
If user select protocol : AWS S3 HTTPS
- Character Set - Character Set provides drop-down to select encoding values from available list. Options are - UTF8, US-ASCII, ISO-8859-1 etc.
- Fail On Error - This property accepts Boolean values i.e. True and False. When 'True', component will fail the job in case any error occurs in FTP component operation. When set to 'False', control will be passed to immediate next component in case of success or failure in component operation.
- Batch - Batch simply accepts a numeric number starting from 0 to maximum 99 and signifies the batch this component will execute in. By default this is 0.
The FTP components applies validations to the mandatory fields. Upon placing the
FTP component on job canvas for the first time (from component palette), the component shows up a warning icon as
mandatory properties are not provided.
The properties window also displays error icon on mandatory fields if it has an incorrect value. The error icon
is displayed on the tab as well, if any of the field within the tab has some error.
If the properties window has some error even after user visit's it once, then the warning icon on the FTP
component on the job canvas changes to error icon. This error icon is removed only when all the mandatory fields are supplied
with correct values.


Somehow foods now have they own leg and running around, your mission is feed our Yellow Hungry Cat and stay away from the Angry Bear (Still dont know why him angry).


Validation
- Introduction
- Validation Quickstart
- Form Request Validation
- Manually Creating Validators
- Working With Error Messages
- Available Validation Rules
- Conditionally Adding Rules
- Validating Arrays
- Validating Passwords
- Custom Validation Rules
Introduction
Laravel provides several different approaches to validate your application's incoming data. It is most common to use the validate
method available on all incoming HTTP requests. However, we will discuss other approaches to validation as well.
Laravel includes a wide variety of convenient validation rules that you may apply to data, even providing the ability to validate if values are unique in a given database table. We'll cover each of these validation rules in detail so that you are familiar with all of Laravel's validation features.
Validation Quickstart
To learn about Laravel's powerful validation features, let's look at a complete example of validating a form and displaying the error messages back to the user. By reading this high-level overview, you'll be able to gain a good general understanding of how to validate incoming request data using Laravel:
Defining The Routes
First, let's assume we have the following routes defined in our routes/web.php
file:
use App\Http\Controllers\PostController;
Route::get('/post/create', [PostController::class, 'create']);
Route::post('/post', [PostController::class, 'store']);
The GET
route will display a form for the user to create a new blog post, while the POST
route will store the new blog post in the database.
Creating The Controller
Next, let's take a look at a simple controller that handles incoming requests to these routes. We'll leave the store
method empty for now:
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class PostController extends Controller
{
/**
* Show the form to create a new blog post.
*
* @return \Illuminate\View\View
*/
public function create()
{
return view('post.create');
}
/**
* Store a new blog post.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
// Validate and store the blog post...
}
}
Writing The Validation Logic
Now we are ready to fill in our store
method with the logic to validate the new blog post. To do this, we will use the validate
method provided by the Illuminate\Http\Request
object. If the validation rules pass, your code will keep executing normally; however, if validation fails, an exception will be thrown and the proper error response will automatically be sent back to the user.
If validation fails during a traditional HTTP request, a redirect response to the previous URL will be generated. If the incoming request is an XHR request, a JSON response containing the validation error messages will be returned.
To get a better understanding of the validate
method, let's jump back into the store
method:
/**
* Store a new blog post.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$validated = $request->validate([
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
// The blog post is valid...
}
As you can see, the validation rules are passed into the validate
method. Don't worry - all available validation rules are documented. Again, if the validation fails, the proper response will automatically be generated. If the validation passes, our controller will continue executing normally.
Alternatively, validation rules may be specified as arrays of rules instead of a single |
delimited string:
$validatedData = $request->validate([
'title' => ['required', 'unique:posts', 'max:255'],
'body' => ['required'],
]);
In addition, you may use the validateWithBag
method to validate a request and store any error messages within a named error bag:
$validatedData = $request->validateWithBag('post', [
'title' => ['required', 'unique:posts', 'max:255'],
'body' => ['required'],
]);
Stopping On First Validation Failure
Sometimes you may wish to stop running validation rules on an attribute after the first validation failure. To do so, assign the bail
rule to the attribute:
$request->validate([
'title' => 'bail|required|unique:posts|max:255',
'body' => 'required',
]);
In this example, if the unique
rule on the title
attribute fails, the max
rule will not be checked. Rules will be validated in the order they are assigned.
A Note On Nested Attributes
If the incoming HTTP request contains "nested" field data, you may specify these fields in your validation rules using "dot" syntax:
$request->validate([
'title' => 'required|unique:posts|max:255',
'author.name' => 'required',
'author.description' => 'required',
]);
On the other hand, if your field name contains a literal period, you can explicitly prevent this from being interpreted as "dot" syntax by escaping the period with a backslash:
$request->validate([
'title' => 'required|unique:posts|max:255',
'v1\.0' => 'required',
]);
Displaying The Validation Errors
So, what if the incoming request fields do not pass the given validation rules? As mentioned previously, Laravel will automatically redirect the user back to their previous location. In addition, all of the validation errors and request input will automatically be flashed to the session.
An $errors
variable is shared with all of your application's views by the Illuminate\View\Middleware\ShareErrorsFromSession
middleware, which is provided by the web
middleware group. When this middleware is applied an $errors
variable will always be available in your views, allowing you to conveniently assume the $errors
variable is always defined and can be safely used. The $errors
variable will be an instance of Illuminate\Support\MessageBag
. For more information on working with this object, check out its documentation.
So, in our example, the user will be redirected to our controller's create
method when validation fails, allowing us to display the error messages in the view:

Create Post

@if ($errors->any())

@foreach ($errors->all() as $error)

{{ $error }}

@endforeach

@endif

Customizing The Error Messages
Laravel's built-in validation rules each has an error message that is located in your application's resources/lang/en/validation.php
file. Within this file, you will find a translation entry for each validation rule. You are free to change or modify these messages based on the needs of your application.
In addition, you may copy this file to another translation language directory to translate the messages for your application's language. To learn more about Laravel localization, check out the complete localization documentation.
XHR Requests & Validation
In this example, we used a traditional form to send data to the application. However, many applications receive XHR requests from a JavaScript powered frontend. When using the validate
method during an XHR request, Laravel will not generate a redirect response. Instead, Laravel generates a JSON response containing all of the validation errors. This JSON response will be sent with a 422 HTTP status code.
The @error
Directive
You may use the @error
Blade directive to quickly determine if validation error messages exist for a given attribute. Within an @error
directive, you may echo the $message
variable to display the error message:

Post Title
<input id="title" type="text" name="title" class="@error('title') is-invalid @enderror">
@error('title')

{{ $message }}

@enderror
Repopulating Forms
When Laravel generates a redirect response due to a validation error, the framework will automatically flash all of the request's input to the session. This is done so that you may conveniently access the input during the next request and repopulate the form that the user attempted to submit.
To retrieve flashed input from the previous request, invoke the old
method on an instance of Illuminate\Http\Request
. The old
method will pull the previously flashed input data from the session:
$title = $request->old('title');
Laravel also provides a global old
helper. If you are displaying old input within a Blade template, it is more convenient to use the old
helper to repopulate the form. If no old input exists for the given field, null
will be returned:
<input type="text" name="title" value="{{ old('title') }}">
A Note On Optional Fields
By default, Laravel includes the TrimStrings
and ConvertEmptyStringsToNull
middleware in your application's global middleware stack. These middleware are listed in the stack by the App\Http\Kernel
class. Because of this, you will often need to mark your "optional" request fields as nullable
if you do not want the validator to consider null
values as invalid. For example:
$request->validate([
'title' => 'required|unique:posts|max:255',
'body' => 'required',
'publish_at' => 'nullable|date',
]);
In this example, we are specifying that the publish_at
field may be either null
or a valid date representation. If the nullable
modifier is not added to the rule definition, the validator would consider null
an invalid date.
Form Request Validation
Creating Form Requests
For more complex validation scenarios, you may wish to create a "form request". Form requests are custom request classes that encapsulate their own validation and authorization logic. To create a form request class, you may use the make:request
Artisan CLI command:
php artisan make:request StorePostRequest
The generated form request class will be placed in the app/Http/Requests
directory. If this directory does not exist, it will be created when you run the make:request
command. Each form request generated by Laravel has two methods: authorize
and rules
.
As you might have guessed, the authorize
method is responsible for determining if the currently authenticated user can perform the action represented by the request, while the rules
method returns the validation rules that should apply to the request's data:
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
];
}
{tip} You may type-hint any dependencies you require within the
rules
method's signature. They will automatically be resolved via the Laravel service container.
So, how are the validation rules evaluated? All you need to do is type-hint the request on your controller method. The incoming form request is validated before the controller method is called, meaning you do not need to clutter your controller with any validation logic:
/**
* Store a new blog post.
*
* @param \App\Http\Requests\StorePostRequest $request
* @return Illuminate\Http\Response
*/
public function store(StorePostRequest $request)
{
// The incoming request is valid...
// Retrieve the validated input data...
$validated = $request->validated();
}
If validation fails, a redirect response will be generated to send the user back to their previous location. The errors will also be flashed to the session so they are available for display. If the request was an XHR request, an HTTP response with a 422 status code will be returned to the user including a JSON representation of the validation errors.
Adding After Hooks To Form Requests
If you would like to add an "after" validation hook to a form request, you may use the withValidator
method. This method receives the fully constructed validator, allowing you to call any of its methods before the validation rules are actually evaluated:
/**
* Configure the validator instance.
*
* @param \Illuminate\Validation\Validator $validator
* @return void
*/
public function withValidator($validator)
{
$validator->after(function ($validator) {
if ($this->somethingElseIsInvalid()) {
$validator->errors()->add('field', 'Something is wrong with this field!');
}
});
}
Stopping On First Validation Failure Attribute
By adding a stopOnFirstFailure
property to your request class, you may inform the validator that it should stop validating all attributes once a single validation failure has occurred:
/**
* Indicates if the validator should stop on the first rule failure.
*
* @var bool
*/
protected $stopOnFirstFailure = true;
Authorizing Form Requests
The form request class also contains an authorize
method. Within this method, you may determine if the authenticated user actually has the authority to update a given resource. For example, you may determine if a user actually owns a blog comment they are attempting to update. Most likely, you will interact with your authorization gates and policies within this method:
use App\Models\Comment;
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
$comment = Comment::find($this->route('comment'));
return $comment && $this->user()->can('update', $comment);
}
Since all form requests extend the base Laravel request class, we may use the user
method to access the currently authenticated user. Also, note the call to the route
method in the example above. This method grants you access to the URI parameters defined on the route being called, such as the {comment}
parameter in the example below:
Route::post('/comment/{comment}');
Therefore, if your application is taking advantage of route model binding, your code may be made even more succinct by accessing the resolved model as a property of the request:
return $this->user()->can('update', $this->comment);
If the authorize
method returns false
, an HTTP response with a 403 status code will automatically be returned and your controller method will not execute.
If you plan to handle authorization logic for the request in another part of your application, you may simply return true
from the authorize
method:
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
{tip} You may type-hint any dependencies you need within the
authorize
method's signature. They will automatically be resolved via the Laravel service container.
Customizing The Error Messages
You may customize the error messages used by the form request by overriding the messages
method. This method should return an array of attribute / rule pairs and their corresponding error messages:
/**
* Get the error messages for the defined validation rules.
*
* @return array
*/
public function messages()
{
return [
'title.required' => 'A title is required',
'body.required' => 'A message is required',
];
}
Customizing The Validation Attributes
Many of Laravel's built-in validation rule error messages contain an :attribute
placeholder. If you would like the :attribute
placeholder of your validation message to be replaced with a custom attribute name, you may specify the custom names by overriding the attributes
method. This method should return an array of attribute / name pairs:
/**
* Get custom attributes for validator errors.
*
* @return array
*/
public function attributes()
{
return [
'email' => 'email address',
];
}
Preparing Input For Validation
If you need to prepare or sanitize any data from the request before you apply your validation rules, you may use the prepareForValidation
method:
use Illuminate\Support\Str;
/**
* Prepare the data for validation.
*
* @return void
*/
protected function prepareForValidation()
{
$this->merge([
'slug' => Str::slug($this->slug),
]);
}
Manually Creating Validators
If you do not want to use the validate
method on the request, you may create a validator instance manually using the Validator
facade. The make
method on the facade generates a new validator instance:
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class PostController extends Controller
{
/**
* Store a new blog post.
*
* @param Request $request
* @return Response
*/
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
if ($validator->fails()) {
return redirect('post/create')
->withErrors($validator)
->withInput();
}
// Store the blog post...
}
}
The first argument passed to the make
method is the data under validation. The second argument is an array of the validation rules that should be applied to the data.
After determining whether the request validation failed, you may use the withErrors
method to flash the error messages to the session. When using this method, the $errors
variable will automatically be shared with your views after redirection, allowing you to easily display them back to the user. The withErrors
method accepts a validator, a MessageBag
, or a PHP array
.
Stopping On First Validation Failure
The stopOnFirstFailure
method will inform the validator that it should stop validating all attributes once a single validation failure has occurred:
if ($validator->stopOnFirstFailure()->fails()) {
// ...
}
Automatic Redirection
If you would like to create a validator instance manually but still take advantage of the automatic redirection offered by the HTTP request's validate
method, you may call the validate
method on an existing validator instance. If validation fails, the user will automatically be redirected or, in the case of an XHR request, a JSON response will be returned:
Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
])->validate();
You may use the validateWithBag
method to store the error messages in a named error bag if validation fails:
Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
])->validateWithBag('post');
Named Error Bags
If you have multiple forms on a single page, you may wish to name the MessageBag
containing the validation errors, allowing you to retrieve the error messages for a specific form. To achieve this, pass a name as the second argument to withErrors
:
return redirect('register')->withErrors($validator, 'login');
You may then access the named MessageBag
instance from the $errors
variable:
{{ $errors->login->first('email') }}
Customizing The Error Messages
If needed, you may provide custom error messages that a validator instance should use instead of the default error messages provided by Laravel. There are several ways to specify custom messages. First, you may pass the custom messages as the third argument to the Validator::make
method:
$validator = Validator::make($input, $rules, $messages = [
'required' => 'The :attribute field is required.',
]);
In this example, the :attribute
placeholder will be replaced by the actual name of the field under validation. You may also utilize other placeholders in validation messages. For example:
$messages = [
'same' => 'The :attribute and :other must match.',
'size' => 'The :attribute must be exactly :size.',
'between' => 'The :attribute value :input is not between :min - :max.',
'in' => 'The :attribute must be one of the following types: :values',
];
Specifying A Custom Message For A Given Attribute
Sometimes you may wish to specify a custom error message only for a specific attribute. You may do so using "dot" notation. Specify the attribute's name first, followed by the rule:
$messages = [
'email.required' => 'We need to know your email address!',
];
Specifying Custom Attribute Values
Many of Laravel's built-in error messages include an :attribute
placeholder that is replaced with the name of the field or attribute under validation. To customize the values used to replace these placeholders for specific fields, you may pass an array of custom attributes as the fourth argument to the Validator::make
method:
$validator = Validator::make($input, $rules, $messages, [
'email' => 'email address',
]);
After Validation Hook
You may also attach callbacks to be run after validation is completed. This allows you to easily perform further validation and even add more error messages to the message collection. To get started, call the after
method on a validator instance:
$validator = Validator::make(...);
$validator->after(function ($validator) {
if ($this->somethingElseIsInvalid()) {
$validator->errors()->add(
'field', 'Something is wrong with this field!'
);
}
});
if ($validator->fails()) {
//
}
Working With Error Messages
After calling the errors
method on a Validator
instance, you will receive an Illuminate\Support\MessageBag
instance, which has a variety of convenient methods for working with error messages. The $errors
variable that is automatically made available to all views is also an instance of the MessageBag
class.
Retrieving The First Error Message For A Field
To retrieve the first error message for a given field, use the first
method:
$errors = $validator->errors();
echo $errors->first('email');
Retrieving All Error Messages For A Field
If you need to retrieve an array of all the messages for a given field, use the get
method:
foreach ($errors->get('email') as $message) {
//
}
If you are validating an array form field, you may retrieve all of the messages for each of the array elements using the *
character:
foreach ($errors->get('attachments.*') as $message) {
//
}
Retrieving All Error Messages For All Fields
To retrieve an array of all messages for all fields, use the all
method:
foreach ($errors->all() as $message) {
//
}
Determining If Messages Exist For A Field
The has
method may be used to determine if any error messages exist for a given field:
if ($errors->has('email')) {
//
}
Specifying Custom Messages In Language Files
Laravel's built-in validation rules each has an error message that is located in your application's resources/lang/en/validation.php
file. Within this file, you will find a translation entry for each validation rule. You are free to change or modify these messages based on the needs of your application.
In addition, you may copy this file to another translation language directory to translate the messages for your application's language. To learn more about Laravel localization, check out the complete localization documentation.
Custom Messages For Specific Attributes
You may customize the error messages used for specified attribute and rule combinations within your application's validation language files. To do so, add your message customizations to the custom
array of your application's resources/lang/xx/validation.php
language file:
'custom' => [
'email' => [
'required' => 'We need to know your email address!',
'max' => 'Your email address is too long!'
],
],
Specifying Attributes In Language Files
Many of Laravel's built-in error messages include an :attribute
placeholder that is replaced with the name of the field or attribute under validation. If you would like the :attribute
portion of your validation message to be replaced with a custom value, you may specify the custom attribute name in the attributes
array of your resources/lang/xx/validation.php
language file:
'attributes' => [
'email' => 'email address',
],
Specifying Values In Language Files
Some of Laravel's built-in validation rule error messages contain a :value
placeholder that is replaced with the current value of the request attribute. However, you may occasionally need the :value
portion of your validation message to be replaced with a custom representation of the value. For example, consider the following rule that specifies that a credit card number is required if the payment_type
has a value of cc
:
Validator::make($request->all(), [
'credit_card_number' => 'required_if:payment_type,cc'
]);
If this validation rule fails, it will produce the following error message:
The credit card number field is required when payment type is cc.
Instead of displaying cc
as the payment type value, you may specify a more user-friendly value representation in your resources/lang/xx/validation.php
language file by defining a values
array:
'values' => [
'payment_type' => [
'cc' => 'credit card'
],
],
After defining this value, the validation rule will produce the following error message:
The credit card number field is required when payment type is credit card.
Available Validation Rules
Below is a list of all available validation rules and their function:
accepted
The field under validation must be "yes"
, "on"
, 1
, or true
. This is useful for validating "Terms of Service" acceptance or similar fields.
active_url
The field under validation must have a valid A or AAAA record according to the dns_get_record
PHP function. The hostname of the provided URL is extracted using the parse_url
PHP function before being passed to dns_get_record
.
after:date
The field under validation must be a value after a given date. The dates will be passed into the strtotime
PHP function in order to be converted to a valid DateTime
instance:
'start_date' => 'required|date|after:tomorrow'
Instead of passing a date string to be evaluated by strtotime
, you may specify another field to compare against the date:
'finish_date' => 'required|date|after:start_date'
after_or_equal:date
The field under validation must be a value after or equal to the given date. For more information, see the after rule.
alpha
The field under validation must be entirely alphabetic characters.
alpha_dash
The field under validation may have alpha-numeric characters, as well as dashes and underscores.
alpha_num
The field under validation must be entirely alpha-numeric characters.
array
The field under validation must be a PHP array
.
When additional values are provided to the array
rule, each key in the input array must be present within the list of values provided to the rule. In the following example, the admin
key in the input array is invalid since it is not contained in the list of values provided to the array
rule:
use Illuminate\Support\Facades\Validator;
$input = [
'user' => [
'name' => 'Taylor Otwell',
'username' => 'taylorotwell',
'admin' => true,
],
];
Validator::make($input, [
'user' => 'array:username,locale',
]);
bail
Stop running validation rules for the field after the first validation failure.
While the bail
rule will only stop validating a specific field when it encounters a validation failure, the stopOnFirstFailure
method will inform the validator that it should stop validating all attributes once a single validation failure has occurred:
if ($validator->stopOnFirstFailure()->fails()) {
// ...
}
before:date
The field under validation must be a value preceding the given date. The dates will be passed into the PHP strtotime
function in order to be converted into a valid DateTime
instance. In addition, like the after
rule, the name of another field under validation may be supplied as the value of date
.
before_or_equal:date
The field under validation must be a value preceding or equal to the given date. The dates will be passed into the PHP strtotime
function in order to be converted into a valid DateTime
instance. In addition, like the after
rule, the name of another field under validation may be supplied as the value of date
.
between:min,max
The field under validation must have a size between the given min and max. Strings, numerics, arrays, and files are evaluated in the same fashion as the size
rule.
boolean
The field under validation must be able to be cast as a boolean. Accepted input are true
, false
, 1
, 0
, "1"
, and "0"
.
confirmed
The field under validation must have a matching field of {field}_confirmation
. For example, if the field under validation is password
, a matching password_confirmation
field must be present in the input.
date
The field under validation must be a valid, non-relative date according to the strtotime
PHP function.
date_equals:date
The field under validation must be equal to the given date. The dates will be passed into the PHP strtotime
function in order to be converted into a valid DateTime
instance.
date_format:format
The field under validation must match the given format. You should use either date
or date_format
when validating a field, not both. This validation rule supports all formats supported by PHP's DateTime class.
different:field
The field under validation must have a different value than field.
digits:value
The field under validation must be numeric and must have an exact length of value.
digits_between:min,max
The field under validation must be numeric and must have a length between the given min and max.
dimensions
The file under validation must be an image meeting the dimension constraints as specified by the rule's parameters:
'avatar' => 'dimensions:min_width=100,min_height=200'
Available constraints are: min_width, max_width, min_height, max_height, width, height, ratio.
A ratio constraint should be represented as width divided by height. This can be specified either by a fraction like 3/2
or a float like 1.5
:
'avatar' => 'dimensions:ratio=3/2'
Since this rule requires several arguments, you may use the Rule::dimensions
method to fluently construct the rule:
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
Validator::make($data, [
'avatar' => [
'required',
Rule::dimensions()->maxWidth(1000)->maxHeight(500)->ratio(3 / 2),
],
]);
distinct
When validating arrays, the field under validation must not have any duplicate values:
'foo.*.id' => 'distinct'
Distinct uses loose variable comparisons by default. To use strict comparisons, you may add the strict
parameter to your validation rule definition:
'foo.*.id' => 'distinct:strict'
You may add ignore_case
to the validation rule's arguments to make the rule ignore capitalization differences:
'foo.*.id' => 'distinct:ignore_case'
The field under validation must be formatted as an email address. This validation rule utilizes the egulias/email-validator
package for validating the email address. By default, the RFCValidation
validator is applied, but you can apply other validation styles as well:
'email' => 'email:rfc,dns'
The example above will apply the RFCValidation
and DNSCheckValidation
validations. Here's a full list of validation styles you can apply:
The filter
validator, which uses PHP's filter_var
function, ships with Laravel and was Laravel's default email validation behavior prior to Laravel version 5.8.
{note} The
dns
andspoof
validators require the PHPintl
extension.
ends_with:foo,bar,...
The field under validation must end with one of the given values.
exclude_if:anotherfield,value
The field under validation will be excluded from the request data returned by the validate
and validated
methods if the anotherfield field is equal to value.
exclude_unless:anotherfield,value
The field under validation will be excluded from the request data returned by the validate
and validated
methods unless anotherfield's field is equal to value. If value is null
(exclude_unless:name,null
), the field under validation will be excluded unless the comparison field is null
or the comparison field is missing from the request data.
exists:table,column
The field under validation must exist in a given database table.
Basic Usage Of Exists Rule
'state' => 'exists:states'
If the column
option is not specified, the field name will be used. So, in this case, the rule will validate that the states
database table contains a record with a state
column value matching the request's state
attribute value.
Specifying A Custom Column Name
You may explicitly specify the database column name that should be used by the validation rule by placing it after the database table name:
'state' => 'exists:states,abbreviation'
Occasionally, you may need to specify a specific database connection to be used for the exists
query. You can accomplish this by prepending the connection name to the table name:
'email' => 'exists:connection.staff,email'
Instead of specifying the table name directly, you may specify the Eloquent model which should be used to determine the table name:
'user_id' => 'exists:App\Models\User,id'
If you would like to customize the query executed by the validation rule, you may use the Rule
class to fluently define the rule. In this example, we'll also specify the validation rules as an array instead of using the |
character to delimit them:
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
Validator::make($data, [
'email' => [
'required',
Rule::exists('staff')->where(function ($query) {
return $query->where('account_id', 1);
}),
],
]);
file
The field under validation must be a successfully uploaded file.
filled
The field under validation must not be empty when it is present.
gt:field
The field under validation must be greater than the given field. The two fields must be of the same type. Strings, numerics, arrays, and files are evaluated using the same conventions as the size
rule.
gte:field
The field under validation must be greater than or equal to the given field. The two fields must be of the same type. Strings, numerics, arrays, and files are evaluated using the same conventions as the size
rule.
image
The file under validation must be an image (jpg, jpeg, png, bmp, gif, svg, or webp).
in:foo,bar,...
The field under validation must be included in the given list of values. Since this rule often requires you to implode
an array, the Rule::in
method may be used to fluently construct the rule:
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
Validator::make($data, [
'zones' => [
'required',
Rule::in(['first-zone', 'second-zone']),
],
]);
When the in
rule is combined with the array
rule, each value in the input array must be present within the list of values provided to the in
rule. In the following example, the LAS
airport code in the input array is invalid since it is not contained in the list of airports provided to the in
rule:
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
$input = [
'airports' => ['NYC', 'LAS'],
];
Validator::make($input, [
'airports' => [
'required',
'array',
Rule::in(['NYC', 'LIT']),
],
]);
in_array:anotherfield.*
The field under validation must exist in anotherfield's values.
integer
The field under validation must be an integer.
{note} This validation rule does not verify that the input is of the "integer" variable type, only that the input is of a type accepted by PHP's
FILTER_VALIDATE_INT
rule. If you need to validate the input as being a number please use this rule in combination with thenumeric
validation rule.
ip
The field under validation must be an IP address.
ipv4
The field under validation must be an IPv4 address.
ipv6
The field under validation must be an IPv6 address.
json
The field under validation must be a valid JSON string.
lt:field
The field under validation must be less than the given field. The two fields must be of the same type. Strings, numerics, arrays, and files are evaluated using the same conventions as the size
rule.
lte:field
The field under validation must be less than or equal to the given field. The two fields must be of the same type. Strings, numerics, arrays, and files are evaluated using the same conventions as the size
rule.
max:value
The field under validation must be less than or equal to a maximum value. Strings, numerics, arrays, and files are evaluated in the same fashion as the size
rule.
mimetypes:text/plain,...
The file under validation must match one of the given MIME types:
'video' => 'mimetypes:video/avi,video/mpeg,video/quicktime'
To determine the MIME type of the uploaded file, the file's contents will be read and the framework will attempt to guess the MIME type, which may be different from the client's provided MIME type.
mimes:foo,bar,...
The file under validation must have a MIME type corresponding to one of the listed extensions.
Basic Usage Of MIME Rule
'photo' => 'mimes:jpg,bmp,png'
Even though you only need to specify the extensions, this rule actually validates the MIME type of the file by reading the file's contents and guessing its MIME type. A full listing of MIME types and their corresponding extensions may be found at the following location:
https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types
min:value
The field under validation must have a minimum value. Strings, numerics, arrays, and files are evaluated in the same fashion as the size
rule.
multiple_of:value
The field under validation must be a multiple of value.
not_in:foo,bar,...
The field under validation must not be included in the given list of values. The Rule::notIn
method may be used to fluently construct the rule:
use Illuminate\Validation\Rule;
Validator::make($data, [
'toppings' => [
'required',
Rule::notIn(['sprinkles', 'cherries']),
],
]);
not_regex:pattern
The field under validation must not match the given regular expression.
Internally, this rule uses the PHP preg_match
function. The pattern specified should obey the same formatting required by preg_match
and thus also include valid delimiters. For example: 'email' => 'not_regex:/^.+$/i'
.
{note} When using the
regex
/not_regex
patterns, it may be necessary to specify your validation rules using an array instead of using|
delimiters, especially if the regular expression contains a|
character.
nullable
The field under validation may be null
.
numeric
The field under validation must be numeric.
password
The field under validation must match the authenticated user's password. You may specify an authentication guard using the rule's first parameter:
'password' => 'password:api'
present
The field under validation must be present in the input data but can be empty.
prohibited
The field under validation must be empty or not present.
prohibited_if:anotherfield,value,...
The field under validation must be empty or not present if the anotherfield field is equal to any value.
prohibited_unless:anotherfield,value,...
The field under validation must be empty or not present unless the anotherfield field is equal to any value.
regex:pattern
The field under validation must match the given regular expression.
Internally, this rule uses the PHP preg_match
function. The pattern specified should obey the same formatting required by preg_match
and thus also include valid delimiters. For example: 'email' =><EMAIL_ADDRESS>.
{note} When using the
regex
/not_regex
patterns, it may be necessary to specify rules in an array instead of using|
delimiters, especially if the regular expression contains a|
character.
required
The field under validation must be present in the input data and not empty. A field is considered "empty" if one of the following conditions are true:
required_if:anotherfield,value,...
The field under validation must be present and not empty if the anotherfield field is equal to any value.
If you would like to construct a more complex condition for the required_if
rule, you may use the Rule::requiredIf
method. This method accepts a boolean or a closure. When passed a closure, the closure should return true
or false
to indicate if the field under validation is required:
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
Validator::make($request->all(), [
'role_id' => Rule::requiredIf($request->user()->is_admin),
]);
Validator::make($request->all(), [
'role_id' => Rule::requiredIf(function () use ($request) {
return $request->user()->is_admin;
}),
]);
required_unless:anotherfield,value,...
The field under validation must be present and not empty unless the anotherfield field is equal to any value. This also means anotherfield must be present in the request data unless value is null
. If value is null
(required_unless:name,null
), the field under validation will be required unless the comparison field is null
or the comparison field is missing from the request data.
required_with:foo,bar,...
The field under validation must be present and not empty only if any of the other specified fields are present and not empty.
required_with_all:foo,bar,...
The field under validation must be present and not empty only if all of the other specified fields are present and not empty.
required_without:foo,bar,...
The field under validation must be present and not empty only when any of the other specified fields are empty or not present.
required_without_all:foo,bar,...
The field under validation must be present and not empty only when all of the other specified fields are empty or not present.
same:field
The given field must match the field under validation.
size:value
The field under validation must have a size matching the given value. For string data, value corresponds to the number of characters. For numeric data, value corresponds to a given integer value (the attribute must also have the numeric
or integer
rule). For an array, size corresponds to the count
of the array. For files, size corresponds to the file size in kilobytes. Let's look at some examples:
// Validate that a string is exactly 12 characters long...
'title' => 'size:12';
// Validate that a provided integer equals 10...
'seats' => 'integer|size:10';
// Validate that an array has exactly 5 elements...
'tags' => 'array|size:5';
// Validate that an uploaded file is exactly 512 kilobytes...
'image' => 'file|size:512';
starts_with:foo,bar,...
The field under validation must start with one of the given values.
string
The field under validation must be a string. If you would like to allow the field to also be null
, you should assign the nullable
rule to the field.
timezone
The field under validation must be a valid timezone identifier according to the timezone_identifiers_list
PHP function.
unique:table,column,except,idColumn
The field under validation must not exist within the given database table.
Specifying A Custom Table / Column Name:
Instead of specifying the table name directly, you may specify the Eloquent model which should be used to determine the table name:
'email' => 'unique:App\Models\User,email_address'
The column
option may be used to specify the field's corresponding database column. If the column
option is not specified, the name of the field under validation will be used.
'email' => 'unique:users,email_address'
Specifying A Custom Database Connection
Occasionally, you may need to set a custom connection for database queries made by the Validator. To accomplish this, you may prepend the connection name to the table name:
'email' => 'unique:connection.users,email_address'
Forcing A Unique Rule To Ignore A Given ID:
Sometimes, you may wish to ignore a given ID during unique validation. For example, consider an "update profile" screen that includes the user's name, email address, and location. You will probably want to verify that the email address is unique. However, if the user only changes the name field and not the email field, you do not want a validation error to be thrown because the user is already the owner of the email address in question.
To instruct the validator to ignore the user's ID, we'll use the Rule
class to fluently define the rule. In this example, we'll also specify the validation rules as an array instead of using the |
character to delimit the rules:
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
Validator::make($data, [
'email' => [
'required',
Rule::unique('users')->ignore($user->id),
],
]);
{note} You should never pass any user controlled request input into the
ignore
method. Instead, you should only pass a system generated unique ID such as an auto-incrementing ID or UUID from an Eloquent model instance. Otherwise, your application will be vulnerable to an SQL injection attack.
Instead of passing the model key's value to the ignore
method, you may also pass the entire model instance. Laravel will automatically extract the key from the model:
Rule::unique('users')->ignore($user)
If your table uses a primary key column name other than id
, you may specify the name of the column when calling the ignore
method:
Rule::unique('users')->ignore($user->id, 'user_id')
By default, the unique
rule will check the uniqueness of the column matching the name of the attribute being validated. However, you may pass a different column name as the second argument to the unique
method:
Rule::unique('users', 'email_address')->ignore($user->id),
Adding Additional Where Clauses:
You may specify additional query conditions by customizing the query using the where
method. For example, let's add a query condition that scopes the query to only search records that have an account_id
column value of 1
:
'email' => Rule::unique('users')->where(function ($query) {
return $query->where('account_id', 1);
})
url
The field under validation must be a valid URL.
uuid
The field under validation must be a valid RFC 4122 (version 1, 3, 4, or 5) universally unique identifier (UUID).
Conditionally Adding Rules
Skipping Validation When Fields Have Certain Values
You may occasionally wish to not validate a given field if another field has a given value. You may accomplish this using the exclude_if
validation rule. In this example, the appointment_date
and doctor_name
fields will not be validated if the has_appointment
field has a value of false
:
use Illuminate\Support\Facades\Validator;
$validator = Validator::make($data, [
'has_appointment' => 'required|boolean',
'appointment_date' => 'exclude_if:has_appointment,false|required|date',
'doctor_name' => 'exclude_if:has_appointment,false|required|string',
]);
Alternatively, you may use the exclude_unless
rule to not validate a given field unless another field has a given value:
$validator = Validator::make($data, [
'has_appointment' => 'required|boolean',
'appointment_date' => 'exclude_unless:has_appointment,true|required|date',
'doctor_name' => 'exclude_unless:has_appointment,true|required|string',
]);
Validating When Present
In some situations, you may wish to run validation checks against a field only if that field is present in the data being validated. To quickly accomplish this, add the sometimes
rule to your rule list:
$v = Validator::make($request->all(), [
'email' => 'sometimes|required|email',
]);
In the example above, the email
field will only be validated if it is present in the $data
array.
{tip} If you are attempting to validate a field that should always be present but may be empty, check out this note on optional fields.
Complex Conditional Validation
Sometimes you may wish to add validation rules based on more complex conditional logic. For example, you may wish to require a given field only if another field has a greater value than 100. Or, you may need two fields to have a given value only when another field is present. Adding these validation rules doesn't have to be a pain. First, create a Validator
instance with your static rules that never change:
use Illuminate\Support\Facades\Validator;
$validator = Validator::make($request->all(), [
'email' => 'required|email',
'games' => 'required|numeric',
]);
Let's assume our web application is for game collectors. If a game collector registers with our application and they own more than 100 games, we want them to explain why they own so many games. For example, perhaps they run a game resale shop, or maybe they just enjoy collecting games. To conditionally add this requirement, we can use the sometimes
method on the Validator
instance.
$v->sometimes('reason', 'required|max:500', function ($input) {
return $input->games >= 100;
});
The first argument passed to the sometimes
method is the name of the field we are conditionally validating. The second argument is a list of the rules we want to add. If the closure passed as the third argument returns true
, the rules will be added. This method makes it a breeze to build complex conditional validations. You may even add conditional validations for several fields at once:
$v->sometimes(['reason', 'cost'], 'required', function ($input) {
return $input->games >= 100;
});
{tip} The
$input
parameter passed to your closure will be an instance ofIlluminate\Support\Fluent
and may be used to access your input and files under validation.
Validating Arrays
Validating array based form input fields doesn't have to be a pain. You may use "dot notation" to validate attributes within an array. For example, if the incoming HTTP request contains a photos[profile]
field, you may validate it like so:
use Illuminate\Support\Facades\Validator;
$validator = Validator::make($request->all(), [
'photos.profile' => 'required|image',
]);
You may also validate each element of an array. For example, to validate that each email in a given array input field is unique, you may do the following:
$validator = Validator::make($request->all(), [
'person.*.email' => 'email|unique:users',
'person.*.first_name' => 'required_with:person.*.last_name',
]);
Likewise, you may use the *
character when specifying custom validation messages in your language files, making it a breeze to use a single validation message for array based fields:
'custom' => [
'person.*.email' => [
'unique' => 'Each person must have a unique email address',
]
],
Validating Passwords
To ensure that passwords have an adequate level of complexity, you may use Laravel's Password
rule object:
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rules\Password;
$validator = Validator::make($request->all(), [
'password' => ['required', 'confirmed', Password::min(8)],
]);
The Password
rule object allows you to easily customize the password complexity requirements for your application, such as specifying that passwords require at least one letter, number, symbol, or characters with mixed casing:
// Require at least 8 characters...
Password::min(8)
// Require at least one letter...
Password::min(8)->letters()
// Require at least one uppercase and one lowercase letter...
Password::min(8)->mixedCase()
// Require at least one number...
Password::min(8)->numbers()
// Require at least one symbol...
Password::min(8)->symbols()
In addition, you may ensure that a password has not been compromised in a public password data breach leak using the uncompromised
method:
Password::min(8)->uncompromised()
Internally, the Password
rule object uses the k-Anonymity model to determine if a password has been leaked via the haveibeenpwned.com service without sacrificing the user's privacy or security.
By default, if a password appears at least once in a data leak, it will be considered compromised. You can customize this threshold using the first argument of the uncompromised
method:
// Ensure the password appears less than 3 times in the same data leak...
Password::min(8)->uncompromised(3);
Of course, you may chain all the methods in the examples above:
Password::min(8)
->letters()
->mixedCase()
->numbers()
->symbols()
->uncompromised()
Defining Default Password Rules
You may find it convenient to specify the default validation rules for passwords in a single location of your application. You can easily accomplish this using the Password::defaults
method, which accepts a closure. The closure given to the defaults
method should return the default configuration of the Password rule. Typically, the defaults
rule should be called within the boot
method of one of your application's service providers:
use Illuminate\Validation\Rules\Password;
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Password::defaults(function () {
$rule = Password::min(8);
return $this->app->isProduction()
? $rule->mixedCase()->uncompromised()
: $rule;
});
}
Then, when you would like to apply the default rules to a particular password undergoing validation, you may invoke the defaults
method with no arguments:
'password' => ['required', Password::defaults()],
Custom Validation Rules
Using Rule Objects
Laravel provides a variety of helpful validation rules; however, you may wish to specify some of your own. One method of registering custom validation rules is using rule objects. To generate a new rule object, you may use the make:rule
Artisan command. Let's use this command to generate a rule that verifies a string is uppercase. Laravel will place the new rule in the app/Rules
directory. If this directory does not exist, Laravel will create it when you execute the Artisan command to create your rule:
php artisan make:rule Uppercase
Once the rule has been created, we are ready to define its behavior. A rule object contains two methods: passes
and message
. The passes
method receives the attribute value and name, and should return true
or false
depending on whether the attribute value is valid or not. The message
method should return the validation error message that should be used when validation fails:
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class Uppercase implements Rule
{
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
return strtoupper($value) === $value;
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return 'The :attribute must be uppercase.';
}
}
You may call the trans
helper from your message
method if you would like to return an error message from your translation files:
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return trans('validation.uppercase');
}
Once the rule has been defined, you may attach it to a validator by passing an instance of the rule object with your other validation rules:
use App\Rules\Uppercase;
$request->validate([
'name' => ['required', 'string', new Uppercase],
]);
Using Closures
If you only need the functionality of a custom rule once throughout your application, you may use a closure instead of a rule object. The closure receives the attribute's name, the attribute's value, and a $fail
callback that should be called if validation fails:
use Illuminate\Support\Facades\Validator;
$validator = Validator::make($request->all(), [
'title' => [
'required',
'max:255',
function ($attribute, $value, $fail) {
if ($value === 'foo') {
$fail('The '.$attribute.' is invalid.');
}
},
],
]);
Implicit Rules
By default, when an attribute being validated is not present or contains an empty string, normal validation rules, including custom rules, are not run. For example, the unique
rule will not be run against an empty string:
use Illuminate\Support\Facades\Validator;
$rules = ['name' => 'unique:users,name'];
$input = ['name' => ''];
Validator::make($input, $rules)->passes(); // true
For a custom rule to run even when an attribute is empty, the rule must imply that the attribute is required. To create an "implicit" rule, implement the Illuminate\Contracts\Validation\ImplicitRule
interface. This interface serves as a "marker interface" for the validator; therefore, it does not contain any additional methods you need to implement beyond the methods required by the typical Rule
interface.
{note} An "implicit" rule only implies that the attribute is required. Whether it actually invalidates a missing or empty attribute is up to you.