Matches function doesn't run - codeigniter

I don't know why matches function doesn't run. I want user introduce a password and confirm it introducing it again. The problem is that when I use matches function in order to compare both passwords Codeigniter indicates that passwords are not equal after introducing both equals.
Here is the code:
public function validacion_registro()
{
$this->input->post('correo');
$this->input->post('usuario');
$this->input->post('contrasenya');
$this->form_validation->set_rules('correo','Dirección de correo','trim|required|valid_email|xss_clean');
$this->form_validation->set_rules('usuario','Nombre de usuario','trim|required|min_length[5]|xss_clean');
$this->form_validation->set_rules('contrasenya','Contraseña','trim|required|md5|xss_clean|matches[repcontrasenya]');
$this->form_validation->set_rules('repcontrasenya','Confirmación de contraseña','trim|required|md5|xss_clean');
$this->form_validation->set_rules('privacidad','Política de privacidad','trim|required|md5|xss_clean');
if ($this->form_validation->run())
{
redirect('anuncios/test');
echo ("validación válida");
}
else {
$this->load->view('anuncios/login');
}
}
The error is in the comparison between contrasenya and repcontrasenya. When both are equal Codigniter indicates that are different.
Whats wrong?
Thanks.

The command: $this->form_validation->run() returns true if you don't have errors.
Modify the code with:
if ($this->form_validation->run() == FALSE)
{
redirect('anuncios/test');
echo ("validación válida");
}
else
{
$this->load->view('anuncios/login');
}

Related

Access and store {field} and {param} tags

In the following document,
https://www.codeigniter.com/userguide3/libraries/form_validation.html#callbacks-your-own-validation-methods
There is a callback function that sets the message,
public function username_check($str)
{
if ($str == 'test')
{
$this->form_validation->set_message('username_check', 'The {field} field can not be the word "test"');
return FALSE;
}
else
{
return TRUE;
}
}
In the output, {field} gets replaced by the name of the 'input key'. Can anyone tell how to store this {field} tag value in a variable as I wan't to use it in my business logic.
The value of {field} is taken from the value passed via the second parameter to set_rules(). For instance.
$this->form_validation->set_rules('username', 'Username', 'callback_username_check');
The word Username will replace {field}. The error message produced using the above will read.
The Username field can not be the word "test"

Magento2: Argument 1 [...] must be an instance of Magento\Framework\App\Helper\Context

First of all, I'm quite new to Magento 2, but I've used Magento 1.x for some time.
I've read a lot about how to solve DI-related problems, but I'm stuck on this one:
Exception #0 (Exception): Recoverable Error: Argument 1 passed to Cefar\AO\Helper\Ao::__construct() must be an instance of Magento\Framework\App\Helper\Context, instance of Magento\Framework\ObjectManager\ObjectManager given, called in .../vendor/magento/framework/ObjectManager/Factory/AbstractFactory.php on line 93 and defined in .../Cefar/AO/Helper/Ao.php on line 11
Many other answers have suggested deleting the var/di and var/generation folders, sometimes var/cache also. While this solves the problem, it occurs again once bin/magento setup:di:compile is run, which means the code cannot be used in a production environment.
I've checked that the Ao class does not instantiate any objects. It also doesn't try to re-make any objects that could be provided by the context given. Here's the code:
namespace Cefar\AO\Helper;
class Ao extends \Magento\Framework\App\Helper\AbstractHelper
{
const DEFAULT_GRID_COLS = 4;
protected $_session;
public function __construct(
\Magento\Framework\App\Helper\Context $context,
\Magento\Customer\Model\Session $session
)
{
parent::__construct($context);
$this->_session = $session;
}
public function getConfig($path)
{
return $this->scopeConfig->getValue($path);
}
public function isActive($url = null, $print = true) {
$active = ($url && strstr($_SERVER['REQUEST_URI'], $url) !== false);
if ($active && $print) {
echo "active";
} else {
return $active;
}
}
public function isLoggedIn()
{
return $this->_session->isLoggedIn();
}
public function limitWords($text = '', $limit = 10, $showDots = true)
{
$words = explode(' ', $text);
$limited = array_slice($words, 0, $limit);
$newText = implode(' ', $limited);
if (count($words) > $limit && $showDots) {
$newText .= '...';
}
return $newText;
}
public function getCurrentGrid()
{
return ($this->_getRequest()->getParam('grid'))
? $this->_getRequest()->getParam('grid')
: self::DEFAULT_GRID_COLS;
}
}
There's nothing particularly special here. I'm confused as to how this is even happening; every other defined class in the extension is getting its DI parameters correctly. Why is the ObjectManager apparatus providing an unwanted argument? The relevant call is given in the error report as:
.../vendor/magento/framework/ObjectManager/Factory/AbstractFactory.php(93): Cefar\AO\Helper\Ao->__construct(Object(Magento\Framework\ObjectManager\ObjectManager))
So it isn't even providing two arguments!
I've also read about providing type hints in a di.xml, but it doesn't seem to be relevant here as both types are part of the Magento libraries? I note that there is an entry for Magento\Framework\App\Helper\Context but not one for Magento\Customer\Model\Session... but that there are framework classes that use ID to import Magento\Customer\Model\Session already which work.
Long story short, this was because of a typo.
Sometimes when the helper was being included, it was being referred to as Cefar\AO\Helper\Ao, and other times, Cefar\AO\Helper\AO. Essentially, the ObjectManager was resolving both of these references to the same class, but it only had type hints for one of the names so it didn't know what to provide to the incorrect one.
A little help would have been nice, Magento! Maybe an error report that the requested class wasn't found? Still, at least this is finally over with.

Is it wrong to parse the verification from Google?

I used the script from here to do the verification.
The $result === FALSE condition was being bypassed regardless of me clicking on the re-captcha validation on my form.
So I decided to manually parse it like so:
The return looks like this if a failure:
{
"success":false,
"error-codes":[
"missing-input-response"
]
}
And if it's success it looks similar but some additional things are attached, but the main thing I targeted was the string "success":true,
With this part of the script directly below the $result variable:
$result_copy = $result;
// remove white spaces everywhere
$mod_res_copy = preg_replace('/\s+/', '', $result_copy);
$success_string = '"success":true';
if(strpos($mod_res_copy, $success_string) !== false) {
$status = "ok";
}else {
$status = "not-ok";
}
if ($status == "not-ok") {
echo "Please complete the captcha to prevent spam.";
exit;
}else {
// trigger database insert of comment or whatever
}
What I want to know is, is this wrong? Can this be spoofed? I'm using PHP as my server-side scripting language.
You are doing way more work than you need, to parse $result.
It is in JSON format, so this is all you need:
$status = json_decode($result)->success ? 'ok' : 'not-ok';

How to validate email with this code?

I have made code with is work great for me, but I want to make email validation to require # on the field. Here is the code
if (!$('#contact_email').val()) {
if ($("#contact_email").parent().next(".validation").length == 0) // only add if not added
{
$("#contact_email").parent().after("<div class='validation' style='color:red;margin-bottom: 20px;'>Ange e-postadress</div>");
}
e.preventDefault(); // prevent form from POST to server
$('#contact_email').focus();
focusSet = true;
} else {
$("#contact_email").parent().next(".validation").remove(); // remove it
}
And the input is
<input type="text" class="form-control" placeholder="E-post" name="Email" id="contact_email" onblur="validate()">
I dont use basic email field because I don't want to be on english.
How can i implement # to be required on this text input. Thank you
Hey Use This function:
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#"]+(\.[^<>()[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
found here:
Validate email address in JavaScript?
Try this for email validation:
function isEmail(email) {
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (email.match(mailformat)) {
return true;
} else {
return false;
}
}
Checking as follows:
if (email != "") {
if (!isEmail(email)) {
alert("invalid");
}
}
You can use regular expression to check for an "#" and a "." field.
Regex:
var regex= /\S+#\S+\.\S+/;
return regex.test(email);
The above code will return true if the regular expression is matched. This expression checks for an # and a . to be present in the given string.
Heres the documentation on .test http://www.w3schools.com/jsref/jsref_regexp_test.asp
I've noticed other answers have better regular expressions as the above will allow for multiple #'s and .'s to be present.

Codeigniter validation--how to limit numerical value?

I simply need to add a validation class that limits a numerical entry from being greater than 24.
Is this possible with CI's default validation classes or will I have to write a custom validation class?
You can use validation rule "greater_than[24]"
like for Example
$this->form_validation->set_rules('your_number_field', 'Your Number', 'numeric|required|greater_than[24]');
There's no maximum or minimum comparison function in the Form Validation Rule Reference, so you can just write your own validation function.
It's pretty straightforward. Something like this should work:
function maximumCheck($num)
{
if ($num > 24)
{
$this->form_validation->set_message(
'your_number_field',
'The %s field must be less than 24'
);
return FALSE;
}
else
{
return TRUE;
}
}
$this->form_validation->set_rules(
'your_number_field', 'Your Number', 'callback_maximumCheck'
);
Sure you can, just make your own validation function and add it as a callback to validation rule. See http://codeigniter.com/user_guide/libraries/form_validation.html#callbacks
Hence, you will have
...
$this->form_validation->set_rules('mynumber', 'This field', 'callback_numcheck');
....
function numcheck($in) {
if (intval($in) > 24) {
$this->form_validation->set_message('numcheck', 'Larger than 24');
return FALSE;
} else {
return TRUE;
}
}

Resources