Laravel validate regex - Email inside text - php

I need to check the presence of any email within a text in a textarea.
If there's any email present the form should fail.
I did regex to fail if there is no email present regex:/[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}/ and it should be easy to do the negation but I'm not having any success.

Add this code into AppServiceProvider boot method:
Validator::extend('not_regex', function($attribute, $value, $parameters, $validator) {
if (!is_string($value) && !is_numeric($value)) {
return false;
}
return !preg_match($parameters[0], $value);
});
And then just use your regex like this:
not_regex:"/[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}/"

I think the best way to solve this is to create your own custom validation rule. This way you can solve this problem using nicely formatted code.

Laravel comes with an "email" validation rule which is very easy to implement. You can read all about it, and other validation methods in this link.

Related

How to add the parameter name in custom validation laravel

I want to ask about custom validation. I make validation for counting the word
Validator::extend('word_count', function($attribute, $value, $parameters, $validator) {
return str_word_count($value) >= $parameters;
});
How can i give name to parameter so that i can use the parameter value in error message?
Based on your question, i will understand you care about the validation message.
If you are looking for validation message mean, you can use custom message like,
If you are using the request file means, there we can use
messages(){
return [
'word_count' => '....', //some message will be here,
];
}
If you are using controller means, then use like
return response()->json('...', 422);
or
here also you can use that above messages function.
I hope, it will help you.If any thing ask here.

Is there a validation rule for "not present"?

I need to check if the key is not set in the array using Laravel validator.
That would be the complete opposite of the "required" validation rule.
Basically the array will be passed to update method if it passes the validation and I want to make sure one column will not be updated.
Is there a way to check if the value "is not present"?
Thank you
EDIT:
I'm currently using Laravel 5
EDIT:
I managed to write my own validation rule by calling Validator::extendImplicit. However I get $value as null to my validation function both when I set it to null or when I don't set it at all. Is there a way to check if the value is set?
I believe I found a solution:
$validator->extendImplicit('not_present', function($attribute, $value, $parameters)
{
return !array_key_exists($attribute, $this->data);
});
I'm not calling extendImplicit statically because the Validator class object is injected to the controller of my class.
I need to access $this->data ($this referring to the Validator object) to make sure the key doesn't exist in the array being validated.
Based on the #MaGnetas answer I came up with this 2 rules that can be applied on any model.
I'm using Laravel 5.4 so putting this lines on your AppServiceProvider.php should work.
The first approach (extendImplicit and array_key_exists)
Validator::extendImplicit('not_present', function($attribute, $value, $parameters, $validator)
{
return !array_key_exists($attribute, $validator->getData());
});
Ussing $validator->getData() we could use the Validator statically.
The second approach (extend and false)
Validator::extend('not_present', function($attribute, $value, $parameters, $validator)
{
return false;
});
You could use extend because we don't need the rule to be executed if the data has not the property (because that's exactly what we want right?)
On the docs:
By default, when an attribute being validated is not present or contains an empty value as defined by the required rule, normal validation rules, including custom extensions, are not run. more info
Important: The only difference is that using extend, empty strings will not run the validation. But if you have setting TrimStrings and ConvertEmptyStringsToNull on your middleware (which AFAIK is the default option) there will be no problem
No there is no build in validtion rule for this, but you can create your own validation rule.
The simplest way to do this:
Validator::extend('foo', function($attribute, $value, $parameters)
{
// Do some stuff
});
And check if key exists.
More information:
http://laravel.com/docs/4.2/validation#custom-validation-rules
For people looking for the not_present logic in 7.x apps (applicable for all versions), remember that you can simply use the validated data array for the same results.
$validatedKeys = $request->validate([
'sort' => 'integer',
'status' => 'in:active,inactive,archived',
]);
// Only update with keys that has been validated.
$model->update(collect($request->all())->only($validatedKeys)->all());
my model has more attributes but only these two should be updatable, therefore I too were looking for an not_present rule but ending up doing this as the results and conceptual logic is the very same. Just from another perspective.
I know this question is really old but you can also use
'email' => 'sometimes|required|not_regex:/^/i',
If the email is present in the request, the regex will match any characters in the request and if the email is an empty string but is present in request the sometimes|required will catch that.

Laravel Form Validation, fail if not empty

I have an input field which needs to be empty, otherwise I want the validation to fail. This is an attempt at stopping spam through a contact form.
I've looked at the documentation for the validation but there's nothing to do this, other than the "max" rule, but this doesn't work.
Any other options?
Here's a clean and (probably) bullet-proof solution:
'mustBeEmpty' => 'present|max:0',
In the method where you are validation, extend/add custom rule:
Validator::extend('mustBeEmpty', function($attr, $value, $params){
if(!empty($attr)) return false;
return true;
});
Then you may use this rule like:
protected $rules = array(
'emptyInputField' => 'mustBeEmpty'
);
Then everything is as usual, just use:
$v = Validator::make(Input::except('_token'), $rules);
if($v->passes()) {
// Passed, means that the emptyInputField is empty
}
There are other ways to do it without extending it like this or extending the Validator class but it's an easy Laravelish way to do it. Btw, there is a package available on Github as Honeypot spam prevention for Laravel applications, you may check that.
For Laravel 8.x and above, you may use the prohibited validation rule:
return [
'emptyInputField' => 'prohibited',
];
In laravel 5.8 you can use sometimes for conditional rules adding. 'email' => 'sometimes|email' . This rules will be applied if there is something present in input field.
You can use the empty rule. Details can be seen here: https://laravel.com/docs/5.2/validation#conditionally-adding-rules

Laravel custom validation issue

I am trying to register a custom validation rule but it does not seem to work. I need either of 2 fields to be filled in. One is a URL(link) field and other is a File input(file_upload).
Here is my custom validation:
Validator::register('file_check', function($attribute, $value, $parameters) {
if (!trim($value) == "" || array_get(Input::file($parameters[0]), 'tmp_name')) {
return true;
}
return false;
});
$messages = array(
'file_check' => 'Please upload a file or provide a link to files.',
);
$rules = array(
'link' => 'url|file_check:file_upload',
'file_upload' => 'mimes:jpg,jpeg,gif,png,psd,ai,bmp,xls,xlsx,doc,docx,zip,rar,7z,txt,pdf'
);
$validation = Validator::make(Input::all(), $rules, $messages);
if ($validation - > fails()) {
return Redirect::to('page') - > with_errors($validation - > errors) - > with_input();
}
Need help :)
EDITED
Also, I just noticed that the validation rule should accept "PSD" files but when I try to upload a PSD file it redirects with the error "Invalid file type".
I am maybe late in party but may be somebody will find it useful, in case you need to create implicit rule which will be called even if field is not present in Input (like required,required_if....) use
Validator::extendImplicit( 'validator_name', function($attribute, $value, $parameters)
{
});
Check this out
I was just struggling with this myself! It turns out that except when a few specific rules are applied to them, Laravel doesn't pass empty fields through the Validator at all. So a custom either-this-or-that rule can't work, since at least one of the two fields is likely to not be visible to it.
You can get around this by moving from the registering-a-new-rule approach to the alternate extend-the-Validator-class approach. Your new class will inherit all the methods of the standard Validator, including a method called "implicit" (you can find the original on line 215 of the standard Validator class), which specifies a whitelist of rules that Laravel should pass fields along to even if they are empty. Add your new rule to that list and you should be good to go.
Jason is right, but there is one thing that can be confusing.
Laravel's 'registering a new rule' approach uses the syntax 'Validator::extend(...'. As described elsewhere, this is convenient when you want to customize in a special situation. However, if you want to add a number of reusable rules, then you probably want to use the extend-the-Validator-class approach. In that case, IF you have a rule conditionally requires something, you need to override the existing implicitRules array with a new one adding your rule.
If the first rules you add don't conditionally require, you will think you have it nailed, then you will spend hours trying to figure out why your new 'RequireWhenBlaBla...' rule is invisible.

What exactly does Yii email's validator validate?

This is probably a silly question, but i could't figure it out. I have the following:
array('email', 'email','message'=>'The email isnĀ“t correct'),
What would this validation validate exactly? That the input text contains '#' and a '.' ?
The validator uses a regular expression to validate the email.
For the specific expression it uses, look at the source. You can then use an online tool like reFiddle to quickly check if the regex matches any particular input.
Yii is a great framework for form validation,today i am going to show you how to validate the email field in the form before submitting.Its very simple just follow the below example.
if you created a user model with email as one attribute then in the rules function add the following code.
public function rules() {
return array(
...
array('email', 'email','checkMX'=>true),
...
); }
thats it

Categories