Equal Fields validation in Symfony 2 - php

I'm trying to implement change password functionality in Symfony 2 project.
I have entity User with validation rules in validation.yml file. In User entity I have field "password" with its validation constraints in validation.yml.
I created form with 2 field 'password' and 'confirmPasswod'. I want to use my entity validation constraints for 'password' field and check equality between 'passwod' and 'confirmPassword' fields. In my contronller I write
$form = $this->createForm(new SymfonyForm\ChangePasswordType(), new Entity\User());
if ($form->isValid())
{..............}
In 'User' entity I don't have 'confirmPasswod' field. So I get error:
Neither property "confirmPassword" nor method "getConfirmPassword()" nor method "isConfirmPassword()" exists in class
Is there any way to use entity-based form validation for some form fields and not entity-based validation for other?
Thanks in advance.

In SymfonyForm\ChangePasswordType you can use something like this:
$builder->add('password', 'repeated', array(
'type' => 'password',
'first_name' => 'Password',
'second_name' => 'Password confirmation',
'invalid_message' => 'Passwords are not the same',
));
Since Symfony 2.1 you can configure options to avoid broken element name (as mentioned in comment)
$builder->add('password', 'repeated', array(
// … the same as before
'first_name' => 'passwd',
'second_name' => 'passwd_confirm',
// new since 2.1
'first_options' => array('label' => 'Password'),
'second_options' => array('label' => 'Password confirmation'),
));

Related

How can I set custom validation error messages from a controller, in Laravel 8?

I am working on a registration form with Laravel 8 and Sanctum.
I have this piece of code in the AuthController to validate the form fields:
public function register(Request $request) {
$fields = $request->validate([
'first_name' => 'required|string,',
'last_name' => 'required|string',
'email' => 'required|string|unique:users,email',
'password' => 'required|string|confirmed',
'accept' => 'accepted',
]);
// More code here
}
I want to display more user-friendly validation error messages.
Rather than changing the validation.php file (resources\lang\en\validation.php), I want to change the set them for the registration form only, in the method above.
The problem
As someone that has used Codeigniter for a long time, I had, in Codeigniter, the posibility to do just that:
$this->form_validation->set_rules('first_name', 'First name', 'required', array('required' => 'The "First name" field is required'));
I was unable to do something similar in Laravel 8.
How do I get the desired result in Laravel 8?
Maybe this can work for ya.
$rules = [
'first_name' => 'required|string,',
'last_name' => 'required|string',
'email' => 'required|string|unique:users,email',
'password' => 'required|string|confirmed',
'accept' => 'accepted'
];
$customMessages = [
'required' => 'The :attribute field is required.'
];
$this->validate($request, $rules, $customMessages);
Also check out the laravel customizing error messages documentation.
The validate function excepts 3 parameters. A) request, B) the rules, C) Custome Messages.
$this->validate($request, $rules, $customMessages); It means define your custom Message Array by key value. Key is the rulename like require. For example:
[
'required' => 'The :attribute is really,really, really required if you use Login!'
'email.required' => 'Without email you dont come in ;-)'
]

Symfony 4 RepeatedType validation not working

i have a problem creating a simple registration form in Symfony 4.
For the password i use the RepeatedType provided by Symfony, but typing in two different password doesn´t produce any errors and it is still possible to submit the form.
->add('password', RepeatedType::class, [
'type' => PasswordType::class,
'invalid_message' => 'The password fields do not match.',
'options' => [
'attr' => [
'class' => 'form-control'
]
],
'required' => $options['req'],
'first_options' => ['label' => 'New Password'],
'second_options' => ['label' => 'Repeat New Password'],
])
Did i make any mistake adding the Password field with the FormBuilder or might the mistake be even located somewhere else?
This is how i use the NewUserType:
$form = $this->createForm(NewUserType::class, new User(), [
'action' => $this->generateUrl('createUser')
]);
return $this->render('admin/account-management.html.twig', [
'form' => $form->createView(),
'accounts' => $this->getDoctrine()->getRepository(User::class)->findAll(),
'user' => $user
]);
This is how i insert the form into HTML using twig:
{{ form(form) }}
You should use isSubmitted to check if form was submitted and isValid method on $form to validate it. Also you don't need another route for creating user.
$form = $this->createForm(NewUserType::class, new User(), [
// this isn't necessary
//'action' => $this->generateUrl('createUser')
]);
if($form->isSubmitted() && $form->isValid()) {
// this should contain your code from 'createUser' action
}
return $this->render('admin/account-management.html.twig', [
'form' => $form->createView(),
'accounts' => $this->getDoctrine()->getRepository(User::class)->findAll(),
'user' => $user
]);

Codeigniter Form Validation Rule for match (password)

I am trying to write Form validation rules in my Controller to submit Change Password form in which I am checking the old password too. I am getting the old password(current) from db and placing it in a hidden input field.
My Rules are simple and are given below
$config=array(
array(
'field' => 'old_password',
'label' => 'oldpass',
'rules' => 'trim|required'
),
array(
'field' => 'conf_password',
'label' => 'connewpass',
'rules' => 'trim|required|matches[password]'
),
array(
'field' => 'password',
'label' => 'newpass',
'rules' => 'trim|required'
)
My hidden input field in the form to save current password is like
<input type="hidden" name="old_pass" value="<?php echo $user['password']?>">
I know that matches(field name) in rules work for matching two field values but Where I am stuck is that the password coming from db is md5 encrypted. How can I encrypt the password coming from form and match with old pass field in the rule?
There is no need of putting old password hash in hidden field. it's not even safe.
you can create callback function for your own custom validation. Notice the comment i have did in following code.
$config=array(
array(
'field' => 'old_password',
'label' => 'oldpass',
'rules' => 'trim|required|callback_oldpassword_check' // Note: Notice added callback verifier.
),
array(
'field' => 'conf_password',
'label' => 'connewpass',
'rules' => 'trim|required|matches[password]'
),
array(
'field' => 'password',
'label' => 'newpass',
'rules' => 'trim|required'
)
In side your controller create a method as below
public function oldpassword_check($old_password){
$old_password_hash = md5($old_password);
$old_password_db_hash = $this->yourmodel->fetchPasswordHashFromDB();
if($old_password_hash != $old_password_db_hash)
{
$this->form_validation->set_message('oldpassword_check', 'Old password not match');
return FALSE;
}
return TRUE;
}
for more details of callback verification visit here
I have not verified above code. But hope you get the way to solve your problem.
Another approach:
if (!$this - > checkValidLogin($username, $old_password)) {
$this - > form_validation - > set_rules('password', 'Password', [
[
'old_password',
function($value) {
return false;
}
]
]);
$this - > form_validation - > set_message('old_password', 'Old password doesn\'t match.');
}
Please use like this, if you are using form validation library, it is working for me.
$this->form_validation->set_rules('password', 'Password', 'required');
$this->form_validation->set_rules('confirm_password', 'Confirm Password', 'required|matches[password]');
Thank You
Edit: Code formatting

ZF2 Captcha validation ignored when using an input filter

I have a form in my ZF2 app with a CAPTCHA element as follows :
$this->add(array(
'type' => 'Zend\Form\Element\Captcha',
'name' => 'captcha',
'attributes' => array(
'class'=>'form-control',
),
'options' => array(
'label' => 'Please verify you are human.',
'captcha' => array('class' => 'Dumb')
),
));
I have an input filter attached to the form that validates the other elements in the form (name, email, message). When this is attached to the form the validation for the CAPTCHA field is ignored when checking if valid.
if ($request->isPost()) {
// set the filter
$form->setInputFilter($form->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) { ...
If i remove the input filter then the CAPTCHA field is validated correctly but obviously the other fields have no validators. What silly mistake am I making? Is there a "CAPTCHA" validator I have to set in the input filter?
The issue is because, I assume that on your form you have created a method called:
getInputFilter();
which overrides the original getInputFilter(),
there are two solutions:
rename your function on your form to be getInputFilterCustom()
and then modify also:
if ($request->isPost()) {
// set the filter
$form->setInputFilter($form->getInputFilterCustom());
or inside your current getInputFilter() add the logic to validate the captcha.
This is my code to add a captcha image control in a ZF2 form :
$this->add(array(
'name' => 'captcha',
'type' => 'Captcha',
'attributes' => array(
'id' => 'captcha',
'autocomplete' => 'off',
'required' => 'required'
),
'options' => array(
'label' => 'Captcha :',
'captcha' => new \Zend\Captcha\Image(array(
'font' => 'public/fonts/arial.ttf',
'imgDir' => 'public/img/captcha',
'imgUrl' => 'img/captcha'
))
),
));
The others form elements are using validators from the input filter, but i didn't use any validators to make it work.
I hope this can help you.
It is because you don't call the parent getInputFilter() within yours. Simply do
public function getInputFilter()
{
parent::getInputFilter();
//... your filters here
}

CodeIgniter 2, DataMapper Validation Rules

I'm using CodeIgniter 2 with DataMapper ORM.
For Users, I have confirm_password and confirm_email fields (plus others) which both aren't fields in the database (table users does not have these fields), but it's just there to show on the sign-up form:
I also have back-end where these 2 fields (confirm_password and confirm_email) do not exist in the form.
public $validation = array(
'first_name' => array(
'label' => 'lang:common_first_name',
'rules' => array('required', 'trim')
),
'last_name' => array(
'label' => 'lang:common_last_name',
'rules' => array('trim')
),
'email' => array(
'label' => 'lang:common_email',
'rules' => array('required', 'trim', 'unique', 'valid_email')
),
'confirm_email' => array(
'label' => 'lang:common_confirm_email',
'rules' => array('matches' => 'email')
),
'password' => array(
'label' => 'lang:common_password',
'rules' => array('required', 'min_length' => 6, 'encrypt')
),
'confirm_password' => array(
'label' => 'lang:common_confirm_password',
'rules' => array('matches' => 'password')
)
);
If I don't make the confirm_email or confirm_email fields required, the validator won't trigger the matches rule.
If I make them required, then the back-end that does not have these fields, triggers the confirm_email and confirm_password, but it shouldn't.
Is it best to include ALL possible validation rules (in the model of course) that we may have in the application?
Is it a good idea to alter these rules in the controller (say remove
confirm_email index from $validation array) when adding user on
back-end?
I appreciate any thoughts.
Thanks
Do you have the latest version of ORM Mapper, according to documentation you can add non database fields.
http://stensi.com/datamapper/pages/validation.html
Also, you can now add validation rules for non-Database Table fields,
such as 'Confirm Email Address' or 'Confirm Password'. For example:
and you don't need required rule for the confirmation fields - as they indicate that filed is required in DB hence the DB error) , - the matches property will do the required validation against the matched field (e.g. if it dosen't match it will throw the error.) In other words you only need required on 'email' field, confirmation_email will throw the error if filed don't match. On empty field you really need to show that email is required.
Finally - you can remove the index, but generally thats not good idea. I would , instead, if above fails - add the form validation rule in controller.

Categories