javascript - Codeigniter and jQuery - Validate form data -
i lots of own coding codeigniter+jquery combo. current project has lot's of different kind of inputs, , when data different, have handle differently. 1 field can email field, 1 field can number field has allow numbers , comma etc. got point.
i made easy example how have been doing things. when submit pressed check every input's data regex match , if wrong, change color of input, , inform on field whats wrong. quite simple.
this method works, when have lots of inputs gets messy , hard maintain, , mean have have php fallback if user have disabled javascript. have same checks on jquery , php side.
other thing security. think i'm paranoid exploits/xss attacks, , remove unwanted characters regex , after check other regex if remaining data valid.
i grateful if tell if there better way achieve data handling/validating between codeigniter , jquery.
application/controllers/example.php
<?php if ( ! defined('basepath')) exit('no direct script access allowed'); class example extends ci_controller { function __construct() { parent::__construct(); $this->load->helper('url'); } public function index() { $this->load->view('example_view'); } public function jquery() { echo "username: ". $this->input->post('username'); echo "userage: ". $this->input->post('userage'); echo "useremail: ". $this->input->post('useremail'); } } ?>
application/views/example_view.php
<!doctype html> <html lang="en-us"> <head> <meta charset="utf-8"> <title>my test</title> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> </head> <body> <div id="status"></div> <br /> <form id="userform"> <label for="username">username:</label> <input type="text" name="username" id="username" /> <br /> <br /> <label for="userage">age:</label> <input type="text" name="userage" id="userage" /> </br > <br /> <label for="useremail">e-mail:</label> <input type="text" name="useremail" id="useremail" /> </br > </br > <input type="submit" name="senddata" value="send it" /> </form> </body> </html> <script> $("#userform").submit(function(event) { event.preventdefault(); var error = 0; if($("#userform").match('/regexp_here/')) { $("#username").addclass('alert'); error++; } else { $("#username").removeclass('alert'); } if($("#userage").match('/regexp_here/')) { $("#userage").addclass('alert'); error++; } else { $("#userage").removeclass('alert'); } if($("#useremail").match('/regexp_here/')) { $("#useremail").addclass('alert'); error++; } else { $("#useremail").removeclass('alert'); } if(error == 0) { $.ajax({ type: 'post', url: 'example/jquery/', data: { username: username, userage: userage, useremail: useremail }, success:function(data) { $("status").html(data); }, error:function() { $("status").html("well, error..."); } }); } else { } }); </script>
Comments
Post a Comment