Validating forms with regex in codeigniter

Asked
Active3 hr before
Viewed126 times

8 Answers

validatingregexforms
90%

1 You need to put the / inside the [] since codeigniter expects the regular expression to be surrounded by []. – Will C. Dec 21 '12 at 0:25 , Are there countries that ban public sector unions, but allow private sector ones? ,Except that this actually won't work in codeigniter apparently (as of March 2011 this was the case anyway), due to how it handles brackets inside the validation rules, so you'll need to use a callback (see here). ,php's preg_match wants your regular expression surrounded by a non alpha-numeric character (usually everyone uses /), change your setRules() to this:

You would place a function like the following in your controller (or of otherwise appropriate scope):

public
function _usernameRegex($userName) {
   if (preg_match('/^[a-z0-9]+$/', $userName)) {
      return TRUE;
   } else {
      return FALSE;
   }
}

You then set the rule to call your function:

set_rules('username', 'Username', 'trim|required|xss_clean|callback__usernameRegex');
load more v
88%

CodeIgniter is a powerful PHP framework with a very small footprint, built for developers who need a simple and elegant toolkit to create full-featured web applications.

< ? phpclass Login extends CI_Controller {
   public
   function __construct() {
      parent::__construct();
   }
   public
   function index() {
      $data['title'] = 'Administration';
      $this - > form_validation - > set_rules('username', 'Username', 'trim|required');
      $this - > form_validation - > set_rules('password', 'Password', 'trim|required|callback_regex');
      if ($this - > form_validation - > run() == FALSE) {
         $this - > load - > view('common/header.tpl', $data);
         $this - > load - > view('common/login.tpl', $data);
         $this - > load - > view('common/footer.tpl');
      } else {
         redirect('common/dashboard');
      }
   }
   public
   function regex($password) {
      if ($password == FALSE) {
         $this - > form_validation - > set_message('regex', 'Password must contain at least one upper case letter');
         return false;
      } else {
         return true;
      }
   }
}
load more v
72%

CodeIgniter lets you set as many validation rules as you need for a given field, cascading them in order, and it even lets you prep and pre-process the field data at the same time. To set validation rules you will use the set_rules() method:,CodeIgniter provides a comprehensive form validation and data prepping class that helps minimize the amount of code you’ll write.,Before moving on it should be noted that the rule setting method can be passed an array if you prefer to set all your rules in one action. If you use this approach, you must name your array keys as indicated:,Reload your form and submit it with the word “test” as the username. You can see that the form field data was passed to your callback method for you to process.

<html>

<head>
   <title>My Form</title>
</head>

<body>

   <?php echo validation_errors(); ?>

   <?php echo form_open('form'); ?>

   <h5>Username</h5>
   <input type="text" name="username" value="" size="50" />

   <h5>Password</h5>
   <input type="text" name="password" value="" size="50" />

   <h5>Password Confirm</h5>
   <input type="text" name="passconf" value="" size="50" />

   <h5>Email Address</h5>
   <input type="text" name="email" value="" size="50" />

   <div><input type="submit" value="Submit" /></div>

   </form>

</body>

</html>
load more v
65%

Though there is no regex_match() method in CodeIgniter validation library, It's not listed in the CI User Guide.,Per @Limon's comment:,the regex in that line is not equivalent to the one I mentioned. ,There is a bug in CodeIgniter with the pipe |, it breaks the regex.

I have this regular expression for validation in javascript:

/^(?:'[A-z](([\._\-][A-z0-9])|[A-z0-9])*[a-z0-9_]*')$/

Now I want the same regular expression for the form validation using Codeigniter's form validation:

$this - > form_validation - > set_rules('username', 'Nombre de usuario', 'required|min_length[2]|max_length[15]|regex_match[/^[A-Z a-z 0-9 _ . \-]+$/]|is_unique[user.username]');
load more v
75%

Validation is an important process while building web application. It ensures that the data that we are getting is proper and valid to store or process. CodeIgniter has made this task very easy. Let us understand this process with a simple example.,CodeIgniter - Form Validation,CodeIgniter - Application Profiling,CodeIgniter - Internationalization

Create a view file myform.php and save the below code it in application/views/myform.php. This page will display form where user can submit his name and we will validate this page to ensure that it should not be empty while submitting.

<html>

<head>
   <title>My Form</title>
</head>

<body>
   <form action="" method="">
      <?php echo validation_errors(); ?>
      <?php echo form_open('form'); ?>
      <h5>Name</h5>
      <input type="text" name="name" value="" size="50" />
      <div><input type="submit" value="Submit" /></div>
   </form>
</body>

</html>
load more v
40%

Welcome to CodeIgniter4,Contributing to CodeIgniter,Validation Placeholders,Using CodeIgniter's Model

<html>

<head>
   <title>My Form</title>
</head>

<body>

   <?= $validation->listErrors() ?>

   <?= form_open('form') ?>

   <h5>Username</h5>
   <input type="text" name="username" value="" size="50" />

   <h5>Password</h5>
   <input type="text" name="password" value="" size="50" />

   <h5>Password Confirm</h5>
   <input type="text" name="passconf" value="" size="50" />

   <h5>Email Address</h5>
   <input type="text" name="email" value="" size="50" />

   <div><input type="submit" value="Submit" /></div>

   </form>

</body>

</html>
load more v
22%

Form Validation in CI,The following is a list of all the native rules that are available to use:,HTML5 Form Validations with Pattern Matching, HTML5 Form Validations with Pattern Matching

Source : https://www.codeigniter.com/userguide3/libraries/form_validation.html
As you can see, some of these rules have a single parameter.
The rule matches[] will return TRUE if the field matches the field name passed to it.
The min_length[], max_length[], and exact_length[] rules will take an integer as a parameter and check if the minimum length, maximum length respectively, or exact length matches the rule.
The rules with no parameters are pretty much self-explanatory. You are able to use more than one rule, simply separate rules with a vertical bar ‘|’ and they will cascade.
The rules
Now that we know how to set rules and what the rules we can use are, we can go ahead and set the rules necessary for our form. All fields should be required, and the e-mail field should be validated to ensure that the e-mail address is correctly formatted.

matches[]
load more v
60%

In this section, we'll go through the basic form validation concepts in CodeIgniter.,In this article, we'll go through the built-in form validation library in the CodeIgniter framework.,In this article, we thoroughly discussed form validation in CodeIgniter. ,So that's it as far as basic validation is concerned in CodeIgniter.

Next, create the view file application/views/validate_form.php as shown below.

<html>
    <head>
	<title>Form Validation Example</title>
	<style>
	.field_title{font-size: 13px;font-family:Arial;width: 300px;margin-top: 10px}
	.form_error{font-size: 13px;font-family:Arial;color:red;font-style:italic}
	</style>
	</head>
	
	<body>
		<div class="form_error">
		  <?php echo validation_errors(); ?>
		</div>
		
		<?php echo form_open(); ?>
		
			<h2>Form Validation Example</h2>
		
			<div>
				<div class="field_title">Text Field One (Required)</div>
				<input type="text" name="text_field" value="<?php echo set_value('text_field'); ?>" size="30" />
			</div>
			
			<div>
				<div class="field_title">Text Field Two (Minimum length)</div>
				<input type="text" name="min_text_field" value="<?php echo set_value('min_text_field'); ?>" size="30" />
			</div>
			
			<div>
				<div class="field_title">Text Field Three (Maximum length)</div>
				<input type="text" name="max_text_field" value="<?php echo set_value('max_text_field'); ?>" size="30" />
			</div>
			
			<div>
				<div class="field_title">Text Field Four (Exact length)</div>
				<input type="text" name="exact_text_field" value="<?php echo set_value('exact_text_field'); ?>" size="30" />
			</div>
			
			<div>
				<div class="field_title">Text Field Five (Alphabets only)</div>
				<input type="text" name="alphabets_text_field" value="<?php echo set_value('alphabets_text_field'); ?>" size="30" />
			</div>
			
			<div>
				<div class="field_title">Text Field Six (Alphanumeric only)</div>
				<input type="text" name="alphanumeric_text_field" value="<?php echo set_value('alphanumeric_text_field'); ?>" size="30" />
			</div>
			
			<div>
				<div class="field_title">Email Field</div>
				<input type="text" name="valid_email_field" value="<?php echo set_value('valid_email_field'); ?>" size="30" />
			</div>
			
			<div>
				<div class="field_title">Password Field</div>
				<input type="password" name="password_field" value="" size="30" />
			</div>
			
			<div>
				<div class="field_title">Password Confirmation Field</div>
				<input type="password" name="password_confirmation_field" value="" size="30" />
			</div>
			
			<div>
				<div class="field_title">IP Field</div>
				<input type="text" name="valid_ip_field" value="<?php echo set_value('valid_ip_field'); ?>" size="30" />
			</div>
			
			<div class="field_title">
				<input type="submit" value="Submit" />
			</div>
		
		</form>
	</body>
</html>
load more v