06 May 2008 203,661 views Show
jQuery Validation adalah sebuah plugin jQuery yang berfungsi untuk mempermudah validasi form client-side. Cara penggunaannya adalah dengan memanggil script jquery dan jquery-validate di dlm kode html anda (biasanya diletakkan di bagian head) :
Ketikkan script validate nya:
Di mana myForm adalah id dari form yg akan divalidasi.
Kemudian di bagian input yg akan kita beri validasi tambahkan class=”required”
Jika field masih kosong, kemudian kita tekan tombol submit, maka akan muncul peringatan bahwa field tsb harus diisi, dan form tidak akan di submit. Pesan yang muncul di sebelah kanan input “This field is required.” itu adalah pesan default. Pesan tersebut bisa kita ganti dengan menambahkan attribute title di input, misalnya:
Maka pesan akan berganti menjadi pesan anda sendiri. Validasi menggunakan jQuery Validation Plugin juga bisa diterapkan di semua jenis input, seperti radio button, checkbox, textarea, select option, dan lain-lain. Anda juga bisa menambahkan validasi yang lebih kompleks, seperti pengecekan alamat email, pengecekan URL, pengecekan jumlah minimal & maksimal karakter, pengecekan jenis file yang akan di upload, dan lain-lain. Demo Validasi Form Anda bisa mendownload source code nya di sini: CATATAN: Validasi form menggunakan javascript/jQuery hanya berguna untuk mempermudah proses pengisian form, namun tidak akan melindungi aplikasi web anda. Untuk keamanan yang lebih baik, anda tetap harus menambahkan validasi secara server-side. CodeIgniter provides a comprehensive form validation and data prepping class that helps minimize the amount of code you’ll write. Table of Contents
Overview¶Before explaining CodeIgniter’s approach to data validation, let’s describe the ideal scenario:
On the receiving end, the script must:
Although there is nothing terribly complex about the above process, it usually requires a significant amount of code, and to display error messages, various control structures are usually placed within the form HTML. Form validation, while simple to create, is generally very messy and tedious to implement. Form Validation Tutorial¶What follows is a “hands on” tutorial for implementing CodeIgniter’s Form Validation. In order to implement form validation you’ll need three things:
Let’s create those three things, using a member sign-up form as the example. The Form¶Using a text editor, create a form called myform.php. In it, place this code and save it to your application/views/ folder: <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> The Success Page¶Using a text editor, create a form called formsuccess.php. In it, place this code and save it to your application/views/ folder: <html> <head> <title>My Form</title> </head> <body> <h3>Your form was successfully submitted!</h3> <p><?php echo anchor('form', 'Try it again!'); ?></p> </body> </html> The Controller¶Using a text editor, create a controller called Form.php. In it, place this code and save it to your application/controllers/ folder: <?php class Form extends CI_Controller { public function index() { $this->load->helper(array('form', 'url')); $this->load->library('form_validation'); if ($this->form_validation->run() == FALSE) { $this->load->view('myform'); } else { $this->load->view('formsuccess'); } } } Try it!¶To try your form, visit your site using a URL similar to this one: example.com/index.php/form/ If you submit the form you should simply see the form reload. That’s because you haven’t set up any validation rules yet. Since you haven’t told the Form Validation class to validate anything yet, it returns FALSE (boolean false) by default. ``The run()`` method only returns TRUE if it has successfully applied your rules without any of them failing. Explanation¶You’ll notice several things about the above pages: The form (myform.php) is a standard web form with a couple exceptions:
The controller (Form.php) has one method: Setting Validation Rules¶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 $this->form_validation->set_rules(); The above method takes three parameters as input:
Here is an example. In your controller (Form.php), add this code just below the validation initialization method: $this->form_validation->set_rules('username', 'Username', 'required'); $this->form_validation->set_rules('password', 'Password', 'required'); $this->form_validation->set_rules('passconf', 'Password Confirmation', 'required'); $this->form_validation->set_rules('email', 'Email', 'required'); Your controller should now look like this: <?php class Form extends CI_Controller { public function index() { $this->load->helper(array('form', 'url')); $this->load->library('form_validation'); $this->form_validation->set_rules('username', 'Username', 'required'); $this->form_validation->set_rules('password', 'Password', 'required', array('required' => 'You must provide a %s.') ); $this->form_validation->set_rules('passconf', 'Password Confirmation', 'required'); $this->form_validation->set_rules('email', 'Email', 'required'); if ($this->form_validation->run() == FALSE) { $this->load->view('myform'); } else { $this->load->view('formsuccess'); } } } Now submit the form with the fields blank and you should see the error messages. If you submit the form with all the fields populated you’ll see your success page. Note The form fields are not yet being re-populated with the data when there is an error. We’ll get to that shortly. Setting Rules Using an Array¶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: $config = array( array( 'field' => 'username', 'label' => 'Username', 'rules' => 'required' ), array( 'field' => 'password', 'label' => 'Password', 'rules' => 'required', 'errors' => array( 'required' => 'You must provide a %s.', ), ), array( 'field' => 'passconf', 'label' => 'Password Confirmation', 'rules' => 'required' ), array( 'field' => 'email', 'label' => 'Email', 'rules' => 'required' ) ); $this->form_validation->set_rules($config); Cascading Rules¶CodeIgniter lets you pipe multiple rules together. Let’s try it. Change your rules in the third parameter of rule setting method, like this: $this->form_validation->set_rules( 'username', 'Username', 'required|min_length[5]|max_length[12]|is_unique[users.username]', array( 'required' => 'You have not provided %s.', 'is_unique' => 'This %s already exists.' ) ); $this->form_validation->set_rules('password', 'Password', 'required'); $this->form_validation->set_rules('passconf', 'Password Confirmation', 'required|matches[password]'); $this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[users.email]'); The above code sets the following rules:
Give it a try! Submit your form without the proper data and you’ll see new error messages that correspond to your new rules. There are numerous rules available which you can read about in the validation reference. Note You
can also pass an array of rules to $this->form_validation->set_rules('username', 'Username', array('required', 'min_length[5]')); Prepping Data¶In addition to the validation method like the ones we used above, you can also prep your data in various ways. For example, you can set up rules like this: $this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[5]|max_length[12]'); $this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[8]'); $this->form_validation->set_rules('passconf', 'Password Confirmation', 'trim|required|matches[password]'); $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email'); In the above example, we are “trimming” the fields, checking for length where necessary and making sure that both password fields match. Any native PHP function that accepts one parameter can be used as a rule, like ``htmlspecialchars()``, ``trim()``, etc. Note You will generally want to use the prepping functions after the validation rules so if there is an error, the original data will be shown in the form. Re-populating the form¶Thus far we have only been dealing with errors. It’s time to repopulate the form field with the submitted data. CodeIgniter offers several helper functions that permit you to do this. The one you will use most commonly is: Open your myform.php view file and update the value in each field using the Don’t forget to include each field name in the :php:func:`set_value()` function calls! <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="<?php echo set_value('username'); ?>" size="50" /> <h5>Password</h5> <input type="text" name="password" value="<?php echo set_value('password'); ?>" size="50" /> <h5>Password Confirm</h5> <input type="text" name="passconf" value="<?php echo set_value('passconf'); ?>" size="50" /> <h5>Email Address</h5> <input type="text" name="email" value="<?php echo set_value('email'); ?>" size="50" /> <div><input type="submit" value="Submit" /></div> </form> </body> </html> Now reload your page and submit the form so that it triggers an error. Your form fields should now be re-populated Note The Class Reference section below contains methods that permit you to re-populate <select> menus, radio buttons, and checkboxes. Important If you use an array as the name of a form field, you must supply it as an array to the function. Example: <input type="text" name="colors[]" value="<?php echo set_value('colors[]'); ?>" size="50" /> For more info please see the Using Arrays as Field Names section below. Callbacks: Your own Validation Methods¶The validation system supports callbacks to your own validation methods. This permits you to extend the validation class to meet your needs. For example, if you need to run a database query to see if the user is choosing a unique username, you can create a callback method that does that. Let’s create an example of this. In your controller, change the “username” rule to this: $this->form_validation->set_rules('username', 'Username', 'callback_username_check'); Then add a new method called <?php class Form extends CI_Controller { public function index() { $this->load->helper(array('form', 'url')); $this->load->library('form_validation'); $this->form_validation->set_rules('username', 'Username', 'callback_username_check'); $this->form_validation->set_rules('password', 'Password', 'required'); $this->form_validation->set_rules('passconf', 'Password Confirmation', 'required'); $this->form_validation->set_rules('email', 'Email', 'required|is_unique[users.email]'); if ($this->form_validation->run() == FALSE) { $this->load->view('myform'); } else { $this->load->view('formsuccess'); } } 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; } } } 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. To invoke a callback just put the method name in a rule, with “callback_” as the rule prefix. If you need to receive an extra parameter in your callback method, just add it normally after the method name between square brackets, as in: Note You can also process the form data that is passed to your callback and return it. If your callback returns anything other than a boolean TRUE/FALSE it is assumed that the data is your newly processed form data. Callable: Use anything as a rule¶If callback rules aren’t good enough for you (for example, because they are limited to your controller), don’t get disappointed, there’s one more way to create custom rules: anything that Consider the following example: $this->form_validation->set_rules( 'username', 'Username', array( 'required', array($this->users_model, 'valid_username') ) ); The
above code would use the This is just an example of course, and callbacks aren’t limited to models. You can use any object/method that accepts the field value as its’ first parameter. You can also use an anonymous function: $this->form_validation->set_rules( 'username', 'Username', array( 'required', function($value) { // Check $value } ) ); Of course, since a Callable rule by itself is not a string, it isn’t a rule name either. That is a problem when you want to set error messages for them. In order to get around that problem, you can put such rules as the second element of an array, with the first one being the rule name: $this->form_validation->set_rules( 'username', 'Username', array( 'required', array('username_callable', array($this->users_model, 'valid_username')) ) ); Anonymous function version: $this->form_validation->set_rules( 'username', 'Username', array( 'required', array( 'username_callable', function($str) { // Check validity of $str and return TRUE or FALSE } ) ) ); Setting Error Messages¶All of the native error messages are located in the following language file: system/language/english/form_validation_lang.php To set your own global custom message for a rule, you can either extend/override the language file by creating your own in application/language/english/form_validation_lang.php (read more about this in the Language Class documentation), or use the following method: $this->form_validation->set_message('rule', 'Error Message'); If you need to set a custom error message for a particular field on some particular rule, use the set_rules() method: $this->form_validation->set_rules('field_name', 'Field Label', 'rule1|rule2|rule3', array('rule2' => 'Error Message on rule2 for this field_name') ); Where rule corresponds to the name of a particular rule, and Error Message is the text you would like displayed. If you’d like to include a field’s “human” name, or the optional parameter some rules allow for (such as max_length), you can add the {field} and {param} tags to your message, respectively: $this->form_validation->set_message('min_length', '{field} must have at least {param} characters.'); On a field with the human name Username and a rule of min_length[5], an error would display: “Username must have at least 5 characters.” Note The old sprintf() method of using %s in your error messages will still work, however it will override the tags above. You should use one or the other. In the callback rule example above, the error message was set by passing the name of the method (without the “callback_” prefix): $this->form_validation->set_message('username_check') Translating Field Names¶If you would like to store the “human” name you passed to the First, prefix your “human” name with lang:, as in this example: $this->form_validation->set_rules('first_name', 'lang:first_name', 'required'); Then, store the name in one of your language file arrays (without the prefix): $lang['first_name'] = 'First Name'; Note If you store your array item in a language file that is not loaded automatically by CI, you’ll need to remember to load it in your controller using: $this->lang->load('file_name'); See the Language Class page for more info regarding language files. Changing the Error Delimiters¶By default, the Form Validation class adds a paragraph tag (<p>) around each error message shown. You can either change these delimiters globally, individually, or change the defaults in a config file.
Showing Errors Individually¶If you prefer to show an error message next to each form field, rather than as a list, you can use the Try it! Change your form so that it looks like this: <h5>Username</h5> <?php echo form_error('username'); ?> <input type="text" name="username" value="<?php echo set_value('username'); ?>" size="50" /> <h5>Password</h5> <?php echo form_error('password'); ?> <input type="text" name="password" value="<?php echo set_value('password'); ?>" size="50" /> <h5>Password Confirm</h5> <?php echo form_error('passconf'); ?> <input type="text" name="passconf" value="<?php echo set_value('passconf'); ?>" size="50" /> <h5>Email Address</h5> <?php echo form_error('email'); ?> <input type="text" name="email" value="<?php echo set_value('email'); ?>" size="50" /> If there are no errors, nothing will be shown. If there is an error, the message will appear. Important If you use an array as the name of a form field, you must supply it as an array to the function. Example: <?php echo form_error('options[size]'); ?> <input type="text" name="options[size]" value="<?php echo set_value("options[size]"); ?>" size="50" /> For more info please see the Using Arrays as Field Names section below. Validating an Array (other than $_POST)¶Sometimes you may want to validate an array that does not originate from In this case, you can specify the array to be validated: $data = array( 'username' => 'johndoe', 'password' => 'mypassword', 'passconf' => 'mypassword' ); $this->form_validation->set_data($data); Creating validation rules, running the validation, and retrieving error messages works the same whether you are validating Important You have to call the Important If you want to validate more than one array during a single execution, then you should call the For more info please see the Class Reference section below. Saving Sets of Validation Rules to a Config File¶A nice feature of the Form Validation class is that it permits you to store all your validation rules for your entire application in a config file. You can organize these rules into “groups”. These groups can either be loaded automatically when a matching controller/method is called, or you can manually call each set as needed. How to save your rules¶To store your validation rules, simply create a file named form_validation.php in your application/config/ folder. In that file you will place an array named $config with your rules. As shown earlier, the validation array will have this prototype: $config = array( array( 'field' => 'username', 'label' => 'Username', 'rules' => 'required' ), array( 'field' => 'password', 'label' => 'Password', 'rules' => 'required' ), array( 'field' => 'passconf', 'label' => 'Password Confirmation', 'rules' => 'required' ), array( 'field' => 'email', 'label' => 'Email', 'rules' => 'required' ) ); Your validation rule file will be loaded automatically and used when you call the Please note
that you MUST name your Creating Sets of Rules¶In order to organize your rules into “sets” requires that you place them into “sub arrays”. Consider the following example, showing two sets of rules. We’ve arbitrarily called these two rules “signup” and “email”. You can name your rules anything you want: $config = array( 'signup' => array( array( 'field' => 'username', 'label' => 'Username', 'rules' => 'required' ), array( 'field' => 'password', 'label' => 'Password', 'rules' => 'required' ), array( 'field' => 'passconf', 'label' => 'Password Confirmation', 'rules' => 'required' ), array( 'field' => 'email', 'label' => 'Email', 'rules' => 'required' ) ), 'email' => array( array( 'field' => 'emailaddress', 'label' => 'EmailAddress', 'rules' => 'required|valid_email' ), array( 'field' => 'name', 'label' => 'Name', 'rules' => 'required|alpha' ), array( 'field' => 'title', 'label' => 'Title', 'rules' => 'required' ), array( 'field' => 'message', 'label' => 'MessageBody', 'rules' => 'required' ) ) ); Calling a Specific Rule Group¶In order to call a specific group, you will pass
its name to the if ($this->form_validation->run('signup') == FALSE) { $this->load->view('myform'); } else { $this->load->view('formsuccess'); } Associating a Controller Method with a Rule Group¶An alternate (and more automatic) method of calling a rule group is to name it according to the controller class/method you intend to use it with. For example, let’s say you have a controller named Member and a method named signup. Here’s what your class might look like: <?php class Member extends CI_Controller { public function signup() { $this->load->library('form_validation'); if ($this->form_validation->run() == FALSE) { $this->load->view('myform'); } else { $this->load->view('formsuccess'); } } } In your validation config file, you will name your rule group member/signup: $config = array( 'member/signup' => array( array( 'field' => 'username', 'label' => 'Username', 'rules' => 'required' ), array( 'field' => 'password', 'label' => 'Password', 'rules' => 'required' ), array( 'field' => 'passconf', 'label' => 'PasswordConfirmation', 'rules' => 'required' ), array( 'field' => 'email', 'label' => 'Email', 'rules' => 'required' ) ) ); When a rule group is named identically to a controller class/method it will be used automatically when the Using Arrays as Field Names¶The Form Validation class supports the use of arrays as field names. Consider this example: <input type="text" name="options[]" value="" size="50" /> If you do use an array as a field name, you must use the EXACT array name in the Helper Functions that require the field name, and as your Validation Rule field name. For example, to set a rule for the above field you would use: $this->form_validation->set_rules('options[]', 'Options', 'required'); Or, to show an error for the above field you would use: <?php echo form_error('options[]'); ?> Or to re-populate the field you would use: <input type="text" name="options[]" value="<?php echo set_value('options[]'); ?>" size="50" /> You can use multidimensional arrays as field names as well. For example: <input type="text" name="options[size]" value="" size="50" /> Or even: <input type="text" name="sports[nba][basketball]" value="" size="50" /> As with our first example, you must use the exact array name in the helper functions: <?php echo form_error('sports[nba][basketball]'); ?> If you are using checkboxes (or other fields) that have multiple options, don’t forget to leave an empty bracket after each option, so that all selections will be added to the POST array: <input type="checkbox" name="options[]" value="red" /> <input type="checkbox" name="options[]" value="blue" /> <input type="checkbox" name="options[]" value="green" /> Or if you use a multidimensional array: <input type="checkbox" name="options[color][]" value="red" /> <input type="checkbox" name="options[color][]" value="blue" /> <input type="checkbox" name="options[color][]" value="green" /> When you use a helper function you’ll include the bracket as well: <?php echo form_error('options[color][]'); ?> Rule Reference¶The following is a list of all the native rules that are available to use:
Note These rules can also be called as discrete methods. For example: $this->form_validation->required($string); Note You can also use any native PHP functions that permit up to two parameters, where at least one is required (to pass the field data). Prepping Reference¶The following is a list of all the prepping methods that are available to use:
Note You can also use any native PHP functions that permits one parameter, like Class Reference¶classCI_Form_validation ¶ set_rules ($field[, $label = ''[, $rules = ''[, $errors = array()]]])¶
Permits you to set validation rules, as described in the tutorial sections above:
run ([$group = ''])¶
Runs the validation routines. Returns boolean TRUE on success and FALSE on failure. You can optionally pass the name of the validation group via the method, as described in: Saving Sets of Validation Rules to a Config File set_message ($lang[, $val = ''])¶
Permits you to set custom error messages. See Setting Error Messages set_error_delimiters ([$prefix = '<p>'[, $suffix = '</p>']])¶
Sets the default prefix and suffix for error messages. set_data ($data)¶
Permits you to set an array for validation, instead of using the default reset_validation ()¶
Permits you to reset the validation when you validate more than one array. This method should be called before validating each new array. error_array ()¶
Returns the error messages as an array. error_string ([$prefix = ''[, $suffix = '']])¶
Returns all error messages (as returned from error_array()) formatted as a string and separated by a newline character. error ($field[, $prefix = ''[, $suffix = '']])¶
Returns the error message for a specific field, optionally adding a prefix and/or suffix to it (usually HTML tags). has_rule ($field)¶
Checks to see if there is a rule set for the specified field. |