在表單提交前進行驗證的幾種方式


1在button的submit事件時判斷

<button type="submit">提交</button>  
("#form").bind("submit",function(){
    var txt_firstname = $.trim($("#firstname").attr("value"));

    var isSuccess = 1;//默認驗證通過
    if(txt_firstname.length == 0){  
        $("#firstnameLabel").text("firstname不能為空!")  
        $("#firstnameLabel").css({"color":"red"});  
        isSuccess = 0;  //驗證不通過,修改isSuccess
   }  
    if(isSuccess == 0){
        return false;//最后未通過,不提交   
    }
})

2 在form的onsubmit判斷

<form id="form" method="post" action="/DealWithForm/" onsubmit="return check()">
function check(){  
    var txt_firstname = $.trim($("#firstname").attr("value"));  

    var isSuccess = 1;  
    if(txt_firstname.length == 0)  
    {  
        $("#firstnameLabel").text("firstname不能為空!")  
        $("#firstnameLabel").css({"color":"red"});  
        isSuccess = 0;  
    }  

    if(isSuccess == 0){  
        return false;  
    } 
    return true;  
}  

注意:onsubmit=“return false”為不執行提交;onsubmit=“return true”或onsubmit=“return ”都執行提交。

3 去掉submit類型button,直接用普通button.

<button type="button" onclick="checktosubmit()">提交</button>  
function checktosubmit(){  
    var txt_firstname = $.trim($("#firstname").attr("value"));
      
    var isSuccess = 1;  
    if(txt_firstname.length == 0)  
    {  
        $("#firstnameLabel").text("firstname不能為空!")  
        $("#firstnameLabel").css({"color":"red"});  
        isSuccess = 0;  
    }  
    if(isSuccess == 1)  
    {  
        form.submit();  
    }  
}

 原文鏈接:http://blog.csdn.net/qian_f/article/details/9631691


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM