11.08.2017 Views

codebright

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Validation 179<br />

22<br />

23 if ($validator->passes()) {<br />

24 // Normally we would do something with the data.<br />

25 return 'Data was saved.';<br />

26 }<br />

27<br />

28 return Redirect::to('/');<br />

29 });<br />

To test the result of the validation we can use the passes() method on the validator instance. This<br />

method will return a boolean response to show whether or not the validation has passed. A true<br />

response indicates that the data conforms to all of the validation rules. A false indicates that the<br />

data does not meet the validation requirements.<br />

We use an if statement in the above example to decide whether to store the data or to redirect to<br />

the entry form. Let’s test this by visiting the / URI.<br />

First enter the value ‘johnzoidberg’ into the username field and hit the submit button. We know<br />

that the username ‘johnzoidberg’ consists of alphanumeric characters, so the validation will pass.<br />

We are presented with the following sentence.<br />

1 Data was saved.<br />

Great, that’s what we expected. Now let’s invert the result of the validation. Go ahead and visit<br />

the / URI once again. This time, enter the value ‘!!!’. We know that an exclamation mark is not an<br />

alphabetical or numerical character, so the validation should fail. Hit the submit button, and we<br />

should be redirected back to the registration form.<br />

I love that passes() method, it’s really useful. The only problem is that it’s a little optimistic. The<br />

world isn’t a perfect place, let’s be honest with ourselves. We aren’t all Robert Downey Jr. Let’s<br />

allow ourselves to be a little more pessimistic shall we? Excellent, wait… satisfactory. Let’s try the<br />

fails() method instead.<br />

1

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!