I have a simple registration form with an address-entity.
I do validate the value of each property using the loadValidatorMetadata(...) {...} method.
I want to check if the email is valide (by characters, etc...) and if email1 is equal to email2 and email1 hasn't to be in the bad-index-array.
Setting the validation is easy. But how can I define different errors-messages for each case?
code example:
public $email;
public $email2;
static function loadValidatorMetadata(ClassMetadata $metadata)
{
...
$metadata->addGetterConstraint('email', new Assert\False(array(
'message' => 'validation.addressFormEmail'
)));
...
}
public function getEmail()
{
if ($this->email == $this->email2) {
return false;
}
return false;
}
Symfony2 has a repeated form type where you can set your message if the value isn't repeated.
then in your entity validation you can set a custom message for email validation.
http://symfony.com/doc/current/reference/forms/types/repeated.html#validation
http://symfony.com/doc/current/reference/constraints/Email.html
Related
I am trying to setup a middleware to check if inputs are empty on form submit for updating a users settings, and if so to return them back to the same page with an error. When I set it up, it gives me the error
Too few arguments to function App\Http\Middleware\AdminUserUpdate::handle(), 2 passed in /var/www/market/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php on line 167 and exactly 3 expected
It seems to be the id I pass through, here is the rest of my code
Middleware:
public function handle(Request $request, Closure $next, $id)
{
if($request->input('username') == NULL) {
return redirect()->route('admin.members.view', $id)->with('error', 'You must enter a username for this user in order to update their account!');
} elseif($request->input('email') == NULL) {
return redirect()->route('admin.members.view', $id)->with('error', 'You must enter a email for this user in order to update their account!');
} elseif($request->input('admin') == NULL) {
return redirect()->route('admin.members.view', $id)->with('error', 'You must select whether this user is a root admin or not in order to update their account!');
} elseif($request->input('banned') == NULL) {
return redirect()->route('admin.members.view', $id)->with('error', 'You must select whether this user is banned or not in order to update their account!');
} elseif($request->input('role') == NULL) {
return redirect()->route('admin.members.view', $id)->with('error', 'You must select a role for this user in order to update their account!');
}
return $next($request);
}
Kernel:
'AdminUserUpdate' => \App\Http\Middleware\AdminUserUpdate::class,
Route:
Route::middleware(['AdminUserUpdate'])->group(function () {
Route::post('/app/members/{id}/submit', 'App\Http\Controllers\Admin\Members\IndexController#Submit')->name('admin.members.submit');
});
I have the ID passed through so I can return them back to the view page for the specific users id, but it doesnt seem to like that for some reason. Anyone have any thoughts?
Middlewares doesn't read route parameters. Use colon to pass a parameter to the middleware.
Route::middleware(['AdminUserUpdate:123'])->group(function () {
Link to Middleware Parameters docs
I suggest to change the way you validate your fields.
In your case, this command create the form validator file
php artisan make:request UpdateUserRequest
In the file UpdateUserRequest.php
This block have all the rules you want to validate
public function rules()
{
return [
'username' => 'required',
'email' => 'required',
... other fields for validation ...
];
}
and inside the store method in your Controller, only this line is required to manipulate all the data after the validation:
$validated = $request->validated();
and for custom messages, add this into your UpdateUserRequest:
public function messages()
{
return [
'username.required' => 'You must enter a username for this user in order to update their account!',
'email.required' => 'You must enter a email for this user in order to update their account!',
... and other validation messages ...
];
}
For more details and ways to validate your forms, check the link:
Form Request Validation
I have created a Yii CActiveForm which has a field experience in it. now i have made the field experience required in the respective Yii model.
Now to want to make it required only a particular condition.
Let's say:
if($entity == 'student') {
// make experience required else make experience optional
}
now I can set a scenario for that purpose for server side validation. but how can I make my view show client validation for experience field as per my new condition.
public function rules()
{
return array(
array('experience', 'myRequired'),
);
}
public function myRequired($attribute, $params)
{
if($this->entity == 'student')
{
$this->addError('Experience cannot be blank.');
return false;
}
return true;
}
Im having trouble with Yii1 validation. I have listbox with contact types and i want email validation to work only when contact via email is choosed. So Im using custom rule to check if its not empty:
public function customEmailValidation($attribute, $params)
{
if(!$this->hasErrors())
{
if($this->contact_type == 2)
{
if($this->attribute == "") $this->addError($attribute, "Enter email address");
}
}
}
But after that I want to use second rule to check if email format is good, how i can achieve it? In main rules i can check it by this:
['email', 'email', 'message' => 'wrong email format'],
but how i can check it only when $this->contact_type == 2 ? I need to write custom rule also and I need to write regex to check email format? Or somehow i can use main validation rules in custom validations?
Thank you.
First remove email validator from rules().
Using your same code, in your custom validation, you can 'attach' any existing Yii validator or create your own / custom validator. In your case, Yii email validator is enough and we will attach it to your custom validation:
public function customEmailValidation($attribute, $params)
{
if(!$this->hasErrors())
{
if($this->contact_type == 2)
{
if($this->attribute == "")
{
$this->addError($attribute, "Enter email address");
}
if( strlen($this->attribute) > 0 )
{
$emailValidator = new CEmailValidator;
if ( ! $emailValidator->validateValue($this->attribute) )
{
$this->addError($attribute, 'Wrong email');
}
}
}
}
}
I have a Yii form accept first name, last name and email from user. Using an add more link, users can add multiple rows of those three elements.
For email validation, unique and required are set in model rules and everything works fine. I am using JavaScript to create addition row on clicking add more link.
Problem
On the first row my values are John, Newman, johnnewman#gmail.com and the second row, i'm entering Mathew, Heyden, johnnewman#gmail.com. In this case email address is duplicated. None of the validation rules (require and unique) is capable of validating this. Can some one suggest a better method to validate this ?
Update:
I created a custom validation function and i guess this is enough to solve my problem. Can someone tell me how to access the whole form data / post data in a custom validation function ?
public function uniqueOnForm($attribute){
// This post data is not working
error_log($_REQUEST, true);
$this->addError($attribute, 'Sorry, email address shouldn\'t be repeated');
}
You can try this:
<?php
public function rules()
{
return array(
array('first_name', 'checkUser')
);
}
public function checkUser($attribute)
{
if($this->first_name == $this->other_first_name){
$this->addError($attribute, 'Please select another first name');
}
}
?>
You can also look into this extension
You can write custom validator:
//protected/extensions/validators
class UniqueMailValidator extends CValidator
{
/**
* #inheritdoc
*/
protected function validateAttribute($object, $attribute)
{
$record = YourModel::model()->findAllByAttributes(array('email' => $object->$attribute));
if ($record) {
$object->addError($attribute, 'Email are exists in db.');
}
}
}
// in your model
public function rules()
{
return array(
array('email', 'ext.validators.UniqueMailValidator'),
...
Or better try to use THIS
public function rules(){
return array(
//other rules
array('email', 'validEmail'),
)
}
public function validEmail($attribute, $params){
if(!empty($this->email) && is_array($this->email)){
$isduplicate = $this->isDuplicate($this->email);
if($isduplicate){
$this->addError('email', 'Email address must be unique!');
}
}
}
private function isDuplicate($arr){
if(count(array_unique($arr)) < count($arr)){
return true;
}
else {
return false;
}
}
because you are using tabular input (multiple row) , so make sure input field as an array. might be like this :
<?php echo $form->textField($model, 'email[]'); ?>
The following is the validation rule
public function rules()
{
return array(
// username and password are required
array('oldPassword', 'required'),
array('oldPassword', 'authenticate'),
....
);
}
public function authenticate($attribute,$params)
{
$this->userModel=User::model()->findByPk(Yii::app()->user->id);
if($this->userModel!=null){
if(!$this->userModel->validatePassword($this->oldPassword))
$this->addError($attribute, "Incorrect current password");
}
}
Everything works fine but the problem lies here... when I keep the oldPassword blank both the validation error for "required" & "authentication' are shown whereas I want to show the error msg for the first one,if not blank then the later.
Add a condition in authenticate() to only validate if oldPassword is not empty:
public function authenticate($attribute, $params) {
if ($this->oldPassword) {
...
}
}