I am building some user profiles and want to add social links to the profiles so users can link to their, let's say Steam, YouTube, Google+ profiles.
So i can't find any way of validating against specific url's in laravel. I want a user, if he set a link in steam text field to validate if given url is really url to steampowered.com, or if not to throw an error that url is not valid.
I have read the documentation on validation and i read that there is a URL validation, but as i have read it's only validating agains the input if it's formated as an url. so basically user can post any url and it will be validated.
Is there a filter or some additional condition to URL validation for a specific url. So the input field will be valid only if user insert like: http://steamcommunity.com in the field.
How can someone achieve that, or i must write old php regex expression?
You should definetely write your own custom Validator and use a regexp to verify that:
\Validator::extend('checkUrl', function($attribute, $value, $parameters)
{
$url = $parameters[0];
//Your pattern, not pretending to be super precise, so it's up to you
$pattern = '/^((http|https)\:\/\/)?(www\.)?'.$url.'\..+$/'
if( preg_match( $pattern,$value)
{
return true;
}
return false;
});
And to use it provide it as a rule to your validator
$rules = [
your_field => 'checkUrl:http://steamcommunity.com'
];
Such a thing is not built in. You can write a custom validation rule and then use regex as you said.
Validator::extend('steam_url', function($attribute, $value, $parameters)
{
$pattern = "#^https?://([a-z0-9-]+\.)*steamcommunity\.com(/.*)?$#";
return !! preg_match($pattern, $value);
});
Usage: 'url' => 'steam_url
Or something more generic:
Validator::extend('domain', function($attribute, $value, $parameters)
{
$domain = $parameters[0];
$pattern = "#^https?://([a-z0-9-]+\.)*".preg_quote($domain)."(/.*)?$#";
return !! preg_match($pattern, $value);
});
Usage: 'url' => 'domain:steamcommunity.com'
Both of your answers are correct guys, however i never liked using regex and i remembered what i did on some site i was making last year to match the website url, and to match it to the point where is no possible for user to input wrong url, and this will also match both http and https. So my final solution is to use parse_url method, very simple and thanks to your examples of validator parameters i can also use it on multiple different domains.
Here's my final code.
Validator::extend('checkUrl', function($attribute, $value, $parameters) {
$url = parse_url($value, PHP_URL_HOST);
return $url == $parameters[0];
EDIT: there is even simpler solution instead of using if method and returning false or true, you can just use return method with option you want to validate.
return $url == $parameters[0];
This would be resolved as
if($url == $parameters[0]) {
return true
} else {
return false
}