Codeigniter appears to always set validation->run to FALSE - codeigniter-3

Controller : User.php
public function index()
{
log_message('debug', ' Index User');
die("should never get here");
}
public function login()
{
log_message('debug', ' Login Entered');
echo '<pre> Printing Login data:';
print_r($_POST);
echo "</pre>";
$data['pageHeader'] = "Login";
$data['message'] = 'temporary message - This will be the login stuff';
$this->session->set_flashdata('flashInfo', 'Login form will go here');
$this->form_validation->set_rules('username', 'Username', 'trim|required');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run() === FALSE)
{
log_message('debug', ' validation run FALSE');
$this->load->helper('form');
$this->render_page('user/login', 'public_header', 'footer', $data);
}
else
{
log_message('debug', ' validation run TRUE');
$remember = (bool) $this->input->post('remember');
if ($this->ion_auth->login($this->input->post('username'), $this->input->post('password'), $remember))
{
log_message('debug', ' redirect Dashboard');
redirect('dashboard');
}
else
{
$_SESSION['auth_message'] = $this->ion_auth->errors();
$this->session->mark_as_flash('auth_message');
log_message('debug', ' redirect user login');
redirect('user/login');
}
}
}
Known from log:
function login entered,
$_POST always 'empty',
form validation-> always FALSE thus debug message is logged and form redisplayed
Form user/login.php
<?php defined('BASEPATH') OR exit('No direct script access allowed');?>
<div class="container">
<?php echo $message;?>
<h1>Login</h1>
<form action="#" method="post">
<div class="imgcontainer">
<img src="http://www.hdkumdo.com/smen/assets/crow2.png" alt="Swordsmen Martial Arts">
</div>
<div class="container">
<label for="username"><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="username" id="username" required autofocus>
<label for="password"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="password" id="password" required>
<button type="submit" name="login" id="login" value"login" >Login</button>
<label>
<input type="checkbox" checked="checked" name="remember" id="remember"> Remember me
</label>
</div>
<div class="container" style="background-color:#f1f1f1">
<button type="button" class="cancelbtn">Cancel</button>
<span class="psw">Forgot password?</span>
</div>
</form>
</div>
Copied an example from https://www.codeigniter.com/user_guide/libraries/form_validation.html
and form posts data but if I change function index to login it does not work.
Menu link : Login works fine.
Everything seems to be connected...login form displays, Controller function login is entered but it seems like there is no POST data so the form is simply redisplayed. I have 2 simple validation rules so it seems that validation->run should return true if I just enter any data into the fields.
I am sure it's something simple but for the life of me I can't see what.

First of all make sure you have loaded form validation library
$this->load->library('form_validation');
//set field validation
$this->form_validation->set_rules('fieldname','Field Name','required');
if($this->form_validation->run())
{
//then process form
//redirect
}
else {
//load view
}

Related

How to redirect back to the page after redirect from that page to login with flask login manager with custom login.html

So i made a login form:
<form action="{{ url_for('login', next=request.endpoint) }}" method="post" class="card-body cardbody-color p-lg-5">
<div class="mb-3">
<input type="text" class="form-control" name="login" placeholder="login" required>
</div>
<div class="mb-3">
<input type="password" class="form-control" name="password" placeholder="password" required>
</div>
<div class="text-center">
<button type="submit" class="btn btn-success px-5 mb-5 w-100">log in</button>
</div>
</form>
key point is:
action="{{ url_for('login', next=request.endpoint) }}"
Thats my login backend:
#server.route("/login", methods=['GET', 'POST'])
def login():
username = request.form.get('login')
password = request.form.get('password')
next_page = request.args.get('next')
if not next_page:
next_page = '/'
if current_user.is_authenticated:
flash('You are already logged in!')
return redirect(url_for('profile'))
if username and password:
user = User.query.filter_by(username=username).first()
if not user:
flash('incorrect login')
return render_template('flask_user/login.html')
if check_password_hash(user.password, password):
login_user(user, remember=True)
return redirect(next_page)
else:
flash('incorrect password')
else:
flash('Enter login and password')
return render_template('flask_user/login.html')
That's my redirect handler:
#login_manager.unauthorized_handler
def redirect_to_signin(response):
return redirect(url_for('login'), next=request.endpoint)
Login manager works perfectly:
http://10.104.4.95:8080/login?next=/arm_analyst
But after i am pressing the log in button, it refreshes the page, so request.endpoint become "login".
I could see only 2 ways of solving this:
to force "next" argument not to change after pressing the log in button
to send from without refreshing
But both looks strange to me because i suppose there is another way to do that.
could anyone help?
I think the problem is the url inside form action, can you set action="" instead of action="{{ url_for('login', next=request.endpoint) }}"

how do you enable/disable submit button based on form contents in Material Design Lite?

I have a submit button for a login form which is disabled by default. I want to enable it when the user enters a valid username/password. There are quite a few examples using AngularJS, JQuery, and other infrastructures but i would like to know a clean way to do it with Material Design Lite. My current code is:
class FrontPage extends Component {
constructor(props, context) {
super(props, context);
this.state = { email: '', password: '' };
}
handleEmailChange() {
this.setState({email: e.target.value})
}
handlePasswordChange() {
this.setState({password: e.target.value})
}
render() {
return(
<form className="frontpage" onSubmit={this.handleLogin}>
<div className="content-grid mdl-grid">
<div className="mdl-cell mdl-textfield mdl-js-textfield">
<input className="mdl-textfield__input" id="email" type="email" value={this.state.email} onChange={this.handleEmailChange}/>
<label className="mdl-textfield__label" htmlFor="email">email...</label>
<span className="mdl-textfield__error">Input is not an email address!</span>
</div>
<div className="mdl-cell mdl-textfield mdl-js-textfield">
<input className="mdl-textfield__input" id="password" type="password" pattern="[A-Z,a-z,0-9\?#\$%&\*\-_=+! ~\.,\/\\]*" value={this.state.password} onChange={this.handlePasswordChange}/>
<label className="mdl-textfield__label" htmlFor="password">password...</label>
<span className="mdl-textfield__error">Input can only contain letters, numbers, and some special characters!</span>
</div>
<div classname="mdl-cell">
<button className="mdl-button mdl-button--raised mdl-button--colored mdl-js-ripple-effect" type="submit" name="login" disabled>Login</button>
</div>
</div>
</form>
)
}
}
<button id='loginBtn' className="mdl-button mdl-button--raised mdl-button--colored mdl-js-ripple-effect" type="submit" name="login" disabled>Login</button>
<script>
function Enable() {
var loginBtn = document.getElementById('loginBtn');
loginBtn.removeAttribute("disabled");
componentHandler.upgradeElement(loginBtn);
}
function Disable() {
var loginBtn = document.getElementById('loginBtn');
loginBtn.setAttribute("disabled","");
componentHandler.upgradeElement(loginBtn);
}
</script>

How to make Confirm Password field in Shopify?

I'm creating a Shopify website, and I'm currently working on the customer registration form. I need to make a Confirm Password field. Does anybody know how to do this in Shopify?
Just Got it working on my register page:
The two password fields:
<div id="create_password_container">
<label for="password">Your Password<em>*</em></label>
<input type="password" value="" name="customer[password]" id="create_password" {% if form.errors contains "password" %} class="error"{% endif %}>
</div>
<div id="password_confirm_container">
<label for="password_confirmation">Password Confirmation</label> <span class="password-match">PASSWORDS DO NOT MATCH</span>
<input type="password" value="" name="customer[password_confirmation]" id="password_confirm" />
</div>
Javascript:
$('form#create_customer').submit(function(e) {
if ( $('#create_password').val() === $('#password_confirm').val()) {
//alert('Password Good!!');
} else {
$('.password-match').fadeIn("slow");
e.preventDefault(); // stops our form from submitting
}
});
The CSS for the password not-matching message:
.password-match {font-size: 12px; color: #f1152f; display:none;}
When customers receive the link to their activation they are prompted for both a password and a password confirmation. Failing that - you can add an extra input (password confirmation) and then do a simple comparison with javascript. Something like:
.... <label for="password" class="login">{{ 'customer.register.password' | t }}</label>
<input type="password" value="" name="customer[password]" id="password" class="large password" size="30" />
<label for="password-confirm" class="login">{{ 'customer.register.password' | t }}</label>
<input type="password" value="" name="customer[password-confirm]" id="password-confirm" class="large password" size="30" /> ....
and then with jquery - something like
$('form').submit(function(e) {
e.preventDefault(); // stops our form from submitting
if ( $('#password').val() === $('#password-confirm').val()) {
$('form').submit();
}
});
That was done off the top of my head - so not tested. It should compare the two password strings - and if they match, allow the form to submit. Of course - you'll probably want to do stuff like show a pop up... alert or message to say your passwords don't match etc. In which case:
$('form').submit(function(e) {
e.preventDefault(); // stops our form from submitting
if ( $('#password').val() === $('#password-confirm').val()) {
$('form').submit();
} else {
// put your validation message in here - this could be showing an element... or showing an alert etc
alert("Your passwords don't match dummy!")
}
});
You could just as easily do
$( ".errorMessage" ).fadeIn( "slow", function() {
// Animation complete
$(this).hide();
});
instead of the alert - but you'd need to make sure you have a div with a class of .errorMessage that contains your error message :)

Yii - Error (and possible solution) validating form with clientValidation active, and using a custom container

I was creating a CActiveForm with the ClientValidation enabled, but stepped in an error when I wrapped a RadioButtonList inside a UL container.
Whenever I submited the form I get a "field cannot be empty" message, even if the radios were checked.
My form:
$form=$this->beginWidget('CActiveForm', array(
'id'=>'enrollment-form',
'enableClientValidation'=>true,
'clientOptions'=>array(
'inputContainer'=>'ul',
'validateOnSubmit'=>true,
),
));
And one of the RadioButtonLists I use:
<div id="drinks">
<?php echo $form->label($model,'drink_id',array('class' => 'title')); ?>
<?php echo $form->radioButtonList($model,'drink_id', CHtml::listData($drinks, 'id', 'name'), array('container'=>'ul', 'template' => '<li class="radio_row">{input}{label}</li>','separator' => '')); ?>
<?php echo $form->error($model,'drink_id'); ?>
</div>
Was I making something wrong?
I studied the code of the jquery.yiiactiveform.js and found that my problem was that in the function that gets the value of the inputs, the value was not taken correctly, because the ID used to identify the inputs was not set in a span, or in the checkboxes/radios themselves (the id was set in the UL container I defined):
var getAFValue = function (o) {
var type,
c = [];
if (!o.length) {
return undefined;
}
if (o[0].tagName.toLowerCase() === 'span') {
o.find(':checked').each(function () {
c.push(this.value);
});
return c.join(',');
}
type = o.attr('type');
if (type === 'checkbox' || type === 'radio') {
return o.filter(':checked').val();
} else {
return o.val();
}
};
So I solved this adding || o[0].tagName.toLowerCase() === 'ul':
var getAFValue = function (o) {
var type,
c = [];
if (!o.length) {
return undefined;
}
if (o[0].tagName.toLowerCase() === 'span' || o[0].tagName.toLowerCase() === 'ul') {
o.find(':checked').each(function () {
c.push(this.value);
});
return c.join(',');
}
type = o.attr('type');
if (type === 'checkbox' || type === 'radio') {
return o.filter(':checked').val();
} else {
return o.val();
}
};
Maybe I was just making some mistake and this solution is just a crappy workaround... but maybe this is just a bug ¿?
The HTML generated:
<form id="enrollment-form" action="/enrollment" method="post">
<div style="display:none"><input type="hidden" value="b06e1d1d796f838f30ba130f8d990034aa9fdad6" name="YII_CSRF_TOKEN" /></div>
<div id="enrollment-form_es_" class="errorSummary" style="display:none"><p>Please fix the following input errors:</p>
<ul><li>dummy</li></ul>
</div>
<div id="drinks">
<label class="title" for="EnrollmentForm_drink_id">Drinks</label>
<input id="ytEnrollmentForm_drink_id" type="hidden" value="" name="EnrollmentForm[drink_id]" />
<ul id="EnrollmentForm_drink_id">
<li class="radio_row">
<input id="EnrollmentForm_drink_id_0" value="2" type="radio" name="EnrollmentForm[drink_id]" />
<label for="EnrollmentForm_drink_id_0">Tea</label>
</li>
<li class="radio_row">
<input id="EnrollmentForm_drink_id_1" value="1" type="radio" name="EnrollmentForm[drink_id]" />
<label for="EnrollmentForm_drink_id_1">Juice</label>
</li>
</ul>
<div class="errorMessage" id="EnrollmentForm_drink_id_em_" style="display:none"></div>
</div>
I noticed that if I didn't use any container when generating the RadioButtonList, Yii aplies a "class=success" to a span. And with my UL container, that class is not generated. When I've changed the Javascript, the class success is generated again.
** The HTML generated without the inputContainer option and without the last array in radioButtonList:
<div id="drinks">
<label class="title" for="EnrollmentForm_drink_id">Bebidas</label>
<input id="ytEnrollmentForm_drink_id" type="hidden" value="" name="EnrollmentForm[drink_id]">
<span id="EnrollmentForm_drink_id">
<input id="EnrollmentForm_drink_id_0" value="2" type="radio" name="EnrollmentForm[drink_id]"> <label for="EnrollmentForm_drink_id_0">Tea</label><br>
<input id="EnrollmentForm_drink_id_1" value="1" type="radio" name="EnrollmentForm[drink_id]"> <label for="EnrollmentForm_drink_id_1">Juice</label>
</span>
<div class="errorMessage" id="EnrollmentForm_drink_id_em_" style="display:none"></div>
</div>
As you can see, Yii generates a strange span that controls if the form is valid or not, by aplying to it the class "success". If I use the inputContainer UL then this class="success" is not generated (with my workaround it is generated and it works).

Form validation with onblur

Here is my form.
<form method="post" name="frm">
<label>Name*<input type="text" name="Name" value="<?php echo $r['Name'] ?>" onblur="if(this.value.length<3) alert('Name too short');" /></label>
<label>Username*<input type="text" name="UN" value="<?php echo $r['UN'] ?>" onblur="if(this.value.length<5) alert('Username too short');" /></label>
<label>Password*<input type="password" name="PW" onblur="validation()" /></label>
<label>Confirm Password*<input type="password" name="CM" onblur="validation()" /></label>
<?php } ?>
<input type="submit" name="Submit" value="<?php if($new) echo 'Register'; else echo 'Update'; ?>" />
</form>
Without writing separate onBlur events I am trying to get all these events into a function called validation() as I have done for password and confirm-password fields. Here is my validation function:
<script language="javascript">
function validation() {
var password = document.frm.PW.value;
var password2 = document.frm.CM.value;
if (password.length < 5) {
alert ("Password too short");
}
else if (password != password2) {
alert("password mismatch");
}
}
</script>
But with this code once I have filled password, and when I am about to start inputting for confirm-password field, it alerts the message "password mismatch". How to get rid of this? And for all the form tags if I am validating and using validation() function, then in each tag do I have to call onblur=validation()?
Don't have the password validation fired on the main password change - have it fired when you alter password2 or when you click submit. :)
If you insist on checking when you update password AND password 2, I would just add a check to see if password2 had been left blank:
else if(password !== password2 && password2 !== ""){
But doing ALL your checks on submit is a much cleaner solution (and as Rake says, it would be neater still to have a span that is updated instead of an alert).