老老鼠

博客园 首页 新随笔 联系 订阅 管理
<fieldset>
    <legend>表单验证</legend>
    <p>
        <label for="username">用户名</label>
        <em>*</em>
        <input id="userName" name="username" size="25" 
            validate='{"rules":{"required":true},"messages":{"required":"请输入用户名"}}' />
    </p>
    <p>
        <label for="email">E-Mail</label>
        <em>*</em><input id="email" name="email" size="25" 
            validate='{"rules":{"required":true,"email":true},
            "messages":{"required":"请输入email","email":"请输入正确的email"}}'/>
    </p>
</fieldset>

/*
 *校验窗体元素
 *<input type="text" name="username" 
 *  validate='{
 *      "rules":{"required":true,"email":true},
 *      "messages":{"required":'请输入用户名',"email":'请输入email'}}'/>
*/
$(document).ready(function () {
    var validate = {
        rules: {},
        messages: {},
        focusInvalid: false,
        onkeyup: false,
        errorPlacement: function (error, element) {
            error.appendTo(element.parent());
        }
    };

    $('*[name]').each(function (index) {
        if ($(this).attr('validate')) {
            eval("var validateinfo=" + $(this).attr('validate'));
            validate.rules[$(this).attr('name')] = validateinfo.rules;
            validate.messages[$(this).attr('name')] = validateinfo.messages;
        }
    });

    $('form').validate(validate);
});
posted on 2010-07-04 23:33  大老鼠  阅读(2253)  评论(0编辑  收藏  举报