Validating forms with regex in codeigniter - php

How can I validate a form using regex in codeiginiter. I'd like to check the input against:
^([0-1][0-9]|[2][0-3]):([0-5][0-9])$
I'm assuming the best way is in some sort of callback. I tried a bunch of ideas on the web but I can't seem to get any working.

Old post but you can add the regex directly in the input validation rule
$this->form_validation->set_rules()
Add to function above: regex_match[your regex]

You can create a function like this:
function validateRegex($input)
{
if (preg_match('/^([0-1][0-9]|[2][0-3]):([0-5][0-9])$/', $input))
{
return true; // it matched, return true or false if you want opposite
}
else
{
return false;
}
}
In your controller, you can use it like:
if ($this->validateRegex($this->input->post('some_data')))
{
// true, proceed with rest of the code.....
}

How about using AJAX?
$("form").submit(function(e) {
e.preventDefault();
$.post("<?php echo base_url(); ?>regex_check", { username: $("#username").val() }, function (data) {
alert(data);
});
The regex_check function would have a typical regex check in it, like
function regex_check(){
$this->get->post('username');
if(eregi('^[a-zA-Z0-9._-]+#[a-zA-Z0-9-] +\.[a-zA-Z.]{2,5}$', $username)){
return TRUE;}else{return FALSE;}
}
You would only allow successful submission of form if all data is validated.
These code snippets should help you on the track to validating the data.

here's a full solution submitting to account/signup
in the account controller:
function signup(){
if($_POST){
$this->form_validation->set_rules('full_name', 'Full Name', 'required|min_length[3]|max_length[100]');
$this->form_validation->set_rules('email_address', 'Email Address', 'required|valid_email');
$this->form_validation->set_rules('password', 'Password', 'required|callback_check_password');
if ($this->form_validation->run() == FALSE){
echo validation_errors();
}
else{
// form validates, now can do stuff such as insert into database
// and show the user that they successfully signed up, i.e.,:
// $this->load->view('account/signup_success');
}
}
}
check_password callback function also in the account controller:
function check_password($p){
$p = $this->input->post('password');
if (preg_match('/(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8}/', $p)) return true;
// it matched, see <ul> below for interpreting this regex
else{
$this->form_validation->set_message('check_password',
'<span class="error">
<ul id="passwordError">
<li> Password must be at least:</li>
<li> 8 characters</li>
<li> 1 upper, 1 lower case letter</li>
<li> 1 number</li>
</ul>
</span>');
return false;
}
}

Related

form validation with preg_match in callback not working

I have questions about my codeigniter form validation. I try to validate the input form for name so it will generate error if user using symbol like ">?<*&%^$". Here is my code:
My rules:
$this->load->library('form_validation');
$this->form_validation->set_rules('full_name', 'Name', 'trim|required|callback_name_check',
array(
'name_check' => '%s should not using symbols'
)
);
This is my callback function (I tried to modify this from the last example I saw, so I thought the problem was here)
public function password_check($str)
{
if (preg_match('#[<>?&%$##]#', $str)) {
return TRUE;
}
return FALSE;
}
I have tried another example from another StackOverflow answer to use / as delimiter (like this --> [/<>?&%$##/]), but still, doesn't work. I'll appreciate your help sensei :)
Validation should be
$this->load->library('form_validation');
$this->form_validation->set_rules('full_name', 'Name', 'trim|required|callback_name_check');
Inside call back function
public function name_check($str)
{
if (preg_match('#[<>?&%$##]#', $str)) {
{
return TRUE;
}
else
{
#adding new validation error should be
$this->form_validation->set_message('full_name', '%s should not using symbols'); # input field name should come to first
return FALSE;
}
}
Note: Didn't validate REGEX which you have posted

Codeigniter: Array Submission Validation

I am having a problem on validating using empty() on codeigniter.
It seemed that it always returns true, empty or not.
<input type="text" name="contactname[]" value="<?php echo set_value('contactname[]');?>">
Model:
if(empty($this->input->post('contactname'))) {
return TRUE;
} else {
return FALSE;
}
I really don't know what's the cause of this issue.
try this
$contactname = $this->input->post('contactname')
if(empty($contactname)) {
return TRUE;
} else {
return FALSE;
}
CodeIgniter provides a comprehensive form validation and data prepping class that helps minimize the amount of code you'll write. You can load library like this in your controller or model :
$this->load->library('form_validation');
To set validation rules you will use the set_rules() function like this :
$this->form_validation->set_rules('contactname[]', 'Contact name', 'required');
So you need to update your code with given below code -
$this->load->library('form_validation');
$this->form_validation->set_rules('contactname[]', 'Contact name', 'required');
if ($this->form_validation->run() == FALSE)
{
echo validation_errors();
}
else
{
// wrire you code here after validation run success
}
For for reference see this link -
http://www.codeigniter.com/userguide2/libraries/form_validation.html
try this
$contact_name = $this->input->post('contactname[]');
if($contact_name != null)
{
return TRUE;
} else{
return FALSE;
}
Try this.
if (count($this->input->post('contactname')) > 0)
return TRUE;
} else {
return FALSE;
}

GROCERY CRUD: set_rules callbacks not working

I tried to validate the password field using a callback function. But when I use the following code, all validations do not work any more WHEN I TYPE 1234 (callback condition). When I remove the validation which contains the callback function, other validations work perfectly..
This is my validation rules
$crud->set_rules('password', 'Password', 'callback_valid_password');
$crud->set_rules('confirm_password', 'Password Confirmation', 'required|matches[password]');
$crud->set_rules('email', 'Email', 'trim|required|valid_email');
Here is my callback function
function valid_password($str) {
if ($str=="1234")
{
$crud->set_message('_valid_password', 'The field should be 1234');
//do some pw validation
return FALSE;
}
else
{
return TRUE;
}
}
Please help me to find what is wrong here.. Thank you in advance
p.s - I am using php 5.4 version with the latest grocery crud version
function valid_password($str) {
if ($str=="1234")
{
$this->form_validation->set_message('valid_password', 'The field should be 1234');
//do some pw validation
return FALSE;
}
else
{
return TRUE;
}
}
For those who are still struggling to find the solution, please follow the checklist.
Are you using CodeIgniter as MVC or HMVC?
1. HMVC
(A) - Check if you have updated the file (./application/libraries/Grocery_crud.php) as suggested below.
(B) - Before "__construct" inside " "class Grocery_CRUD extends grocery_CRUD_States" add "protected $hmvc;"
(C) - Update "__construct" with as below:
public function __construct($hmvc = null)
{
$this->hmvc = $hmvc;
}
(D) - Update "form_validation" with as below:
protected function form_validation()
{
if ($this->form_validation === null) {
$this->form_validation = new grocery_CRUD_Form_validation();
if ($this->hmvc) $this->form_validation->CI = $this->hmvc;
$ci = &get_instance();
$ci->load->library('form_validation');
$ci->form_validation = $this->form_validation;
}
return $this->form_validation;
}
(E) - Use "$crud = new Grocery_crud($this);" instead "$crud = new Grocery_crud();" in your Controller.
(F) - GC set_rules example:
$crud->set_rules("level_title", 'Level Title Label', 'trim|required|callback_unique_level_field_check');
(G) - Callback method example:
public function unique_level_field_check ($level_title)
{
if ( empty($level_title))
{
$this->form_validation->set_message('unique_level_field_check', "Level Title Label should be unique");
return FALSE;
}
return TRUE;
}
2. MVC
Follow F & G only (above).
GroceryCRUD Forum: See details here

Callback function in Codeigniter with multiple parameters during form validation

In Codeigniter:
Here is the callback function that I am using for validation:
public function has_match($password, $username){
if (0) {
// user exists
return true;
}
else {
$this->form_validation->set_message('has_match', 'Invalid Username/password entered ' . $password . ' ' . $username);
return false;
}
}
Below are the validation rules:
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required|callback_has_match[username]');
Can any one please tell me what I am doing wrong here in calling the callback function, as I am unable to get the value of the username field and it keeps showing 'username' (inside the variable $username in callback) instead?
Your code is working as expected. You're basically always calling the callback method has_match with the string username as a parameter. I think that you expect that this translates into:
callback_has_match[$username]
Therefore, when you access the has_match() method, you would have access to the value of $username. This is however, not the way callback methods work. The parameter that you set in there is a string, which is hardcoded, exactly like you do when you add a rule for min_length[10] - it's not the value of a PHP variable. An easy fix, which I haven't tested but suspect works is to do:
$this->form_validation->set_rules('password', 'Password', 'required|callback_has_match[' . $username . ']');
However the code above is not clean, and seems bad design in my opinion.
Now that we've found the problem with the code, I know it's outside the scope of the question, but I would like to point it out - I find it's more of a design issue here. Why do you want to check for the username/password pair inside of a callback to the password field?
Remember, you're validating a form, you shouldn't mix it up with model work. The form doesn't care if the provided username/password combo is correct, it should just look at whether both the fields have been provided correctly, and if so, it should do something about it.
I would adapt your code above to:
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required|callback_has_match[username]');
if ($this->form_validation->run() != FALSE) {
$validLogin = $this->muser->checkLogin($username, $password);
if ($validLogin) {
//Username/password combo exists in DB, save in session or whatever.
} else {
//Username/password combo does not exist in DB, show an error.
}
} else {
//Code for when form fields have not been provided correctly.
}
Instead of sending parameters with call back you can always get them with post
Here is your call back
public function has_match(){
if (0) {
// user exists
return true;
}
else {
$password = $this->input->post('password');
$username = $this->input->post('username');
$this->form_validation->set_message('has_match', 'Invalid Username/password entered ' . $password . ' ' . $username);
return false;
}
}
// CALLBACKS
public function check_user(){
$result = FALSE;
$username=$this->input->post('username');
$email=$this->input->post('emailad');
$dbmember=$this->members->get_members();
foreach ( $dbmember as $key){
// condition of username and email
if($username==$key && $email==$key){
if($username == $key->UserName && $email == $key->EmailAddress){
$this->form_validation->set_message('check_user','already existed!
Please check username and email agian.');
return FALSE;
break;
}
return TRUE;
}
}

Codeigniter use form validation for variable

I've read somewhere that is possible to use Codeigniter's Form Validation also for my own variables and not only for form's inputs.
For example I'd like to validate a url to say if it is valid but not retrieving it using POST or GET from a form.
Do you know how or have a link?
What you are looking for are the callbacks of the Form Validation Class in CodeIgniter - read the user guide for an in-depth explanation.
For PHP5 above version,you can do this
function validdate_urls($str) {
if(!filter_var($str, FILTER_VALIDATE_URL))
{
$this->validation->set_message('validate_urls', 'URL Invalid');
return 0;
}else {
return TRUE;
}
}
And call it in your validation rules :-
$rules['link'] = "callback_validate_urls";
Yes you can via set_data() method, Here you go.
$this->form_validation->set_data(array(
'cartId' => $cartId
));
$this->form_validation->set_rules('cartId', 'Card ID', 'trim|required|is_natural_no_zero');
if ($this->form_validation->run() == FALSE) {
echo 'Invalid: ' . validation_errors();
} else {
echo 'Valid';
}

Categories