Reputation: 1019
I want to validate a website address using php validate url function but i dont know how to achieve this. BTW i tried in this way but it doesnot work.
$url=filter_var($request->website, FILTER_VALIDATE_URL);
'website' => 'required|same:,'.$url
if someone can help me it would be great.
Upvotes: 4
Views: 16744
Reputation: 1791
I know I am a bit late to answer, but I learnt to create the regular expressions last night when I came across this same issue and as a matter of fact, this is the very first regular expression that I have created. So far I was able to solve my problem.
Php: 8.0.3
Laravel: 7.x
app/Rules/DomainNameRule.php
class DomainNameRule implements Rule
{
/**
* Create a new rule instance.
*
* @return void
*/
public function __construct(
private $caption = 'Website'
) {
$this->caption = $caption;
}
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
return preg_match("/^((https?:\/\/)?([w]{3}[\.])?)?[a-zA-Z0-9\-_]{2,}[\.][a-zA-Z]{2,4}([\.][a-zA-Z]{2,6})?$/", $value);
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return @implode('<br>', [
"{$this->caption} - Invalid",
"- Can start with 'http://www' or 'https://www'",
"- Must has a domain name (google | microsoft | yahoo | .etc)",
"- Must end with domain type (.com | .co.in | .online | .etc)",
"- Special characters allowed: _-",
"e.g. https://www.google.com | https://www.google.co.in"
]);
}
}
use App\Rules\DomainNameRule;
...
'website' => ['required', new DomainNameRule];
Here is the link of the youtube video which was quite helpful while I was learning to create the regular expressions: https://youtu.be/zAAXtLo0zuw
Upvotes: 0
Reputation: 2872
You can use url
validator by Laravel
https://laravel.com/docs/5.8/validation#rule-url
'website' => 'required|url'
Or, if you want to build more precise rule, there is a few ways to do it. There is one of them, the simplest in my opinion:
In your AppServiceProvider@boot
:
Validator::extend('website', function ($attribute, $value, $parameters, $validator) {
// validation logic, e.g
return filter_var($value, FILTER_VALIDATE_URL);
});
And then use you rule in validators list:
'website' => ['required', 'website'],
Everything explained here: https://laravel.com/docs/5.8/validation#custom-validation-rules
Upvotes: 7
Reputation: 2945
Laravel uses filter_var()
with the FILTER_VALIADTE_URL
option which doesn't allow umlauts. You can write a custom validator or use the regex validation rule in combination with a regular expression.
$regex ="/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)/";
// specify the rules as array to avoid problems with special characters:
"website" => array("required", "regex:".$regex)
Upvotes: 0