表单验证
< form method ="post" action ="" > < div class ="int" > < label for ="username" > 用户名: </ label > < input type ="text" id ="username" class ="required" /> </ div > < div class ="int" > < label for ="email" > 邮箱: </ label > < input type ="text" id ="email" class ="required" /> </ div > < div class ="int" > < label for ="personinfo" > 个人资料: </ label > < input type ="text" id ="personinfo" class ="required" /> </ div > < div class ="sub" > < input type ="submit" id ="send" value ="提交" />< input type ="reset" id ="res" /> </ div > </ form >
为required属性添加一个星号标识。
$("form :input.required").each(function(){
var $required = $("<strong class='high'>*</strong>"); //创建元素
$(this).parent().append($required); //将它追加到文档中
})
进行表单验证:
$( ' form :input ' ).blur( function (){ // 添加失去焦点事件 var $parent = $( this ).parent();$parent.find( " .formtips " ).remove(); // 删除以前的提醒元素 // 验证用户名 if ($( this ).is( ' #username ' )){ if ( this .value == "" || this .value.length < 6 ){ var errorMsg = ' 请输入至少6位的用户名. ' $parent.append( ' <span class="formtips onError"> ' + errorMsg + ' </span> ' );} else { var okMsg = ' 输入正确 ' ; $parent.append( ' <span class="formtips onSuccess"> ' + okMsg + ' </span> ' );}}}).keyup( function (){$( this ).triggerHandler( " blur " );}).forcus( function (){ $( this ).triggerHandler( " blur " );}) // 点击提交时,再次对所有的表单元素进行验证 $( ' #send ' ).click( function (){ $( " form .required:input " ).trigger( ' blur ' ); var numError = $( ' form .onError ' ).length; if (numError) return false ;});