simple form-validation with jquery

Jaffo (Tel Aviv, Israel), by Christoph Burmeister (own photo)

Jaffo (Tel Aviv, Israel), by Christoph Burmeister (own photo)


Creating a form is easy… event with some not-so-nice table-tags, some tr’s and some td’s and so on. But what if you have a requirement like a valid email-adress? Sure, serverside-validation with PHP is on option, but I heard of a library called JQuery 🙂 Just head-out for the 1st class documentation of jquery and soon found what I desired:

<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>
<script type="text/javascript">
  $(document).ready(function(){
    $("#registrationForm").validate({
        rules: {
            name: "required", // as simple as name:{require: true}
            fname: "required",
            email: {
                required: true,
                email: true // this is for the mail-regex
            }
            
        },
        messages: {
            name: "<i>Please enter your name.</i>",
            fname: "<i>Please enter your forname</i>",
            email: "<i>Please enter a valid email-adress.</i>",       
        }
    });
  });
  </script>
<style type="text/css">
<!--
table {
    border: 1px solid #333;
}
-->
</style>
</head>
<body>    
    <div align="center">
        <form id="registrationForm" method="post" action="./index.php">
            <table>
                <tr>
                    <td>Name</td> 
                    <td><input id="name" name="name" size="25" /></td>
                </tr>
                <tr>
                    <td>Vorname</td>
                    <td><input id="fname" name="fname" size="25" /></td>
                </tr>
                <tr>
                    <td>Email</td>
                    <td><input id="email" name="email" size="25" /></td>
                </tr>
                <tr>
                    <td></td>
                    <td><input class="submit" type="submit" value="register" /></td>
                </tr>
            </table>
        </form>
    </div>
</body>
</html>

That’s all. Thank’s to to guys from JQuery.