2014-09-29 80 views
0

Noob這裏想知道如何使用javascript函數驗證兩個字段。 例如在線javascoipt代碼需要驗證兩個領域fieldx和fieldy關於提交的Javascript已提交

function checkdate(input) { 
var validformat = /^\d{2}\/\d{2}\/\d{4}$/ //Basic check for format validity 
var returnval = false 
if (!validformat.test(input.value)) 
    alert("Invalid Date Format. Please correct and submit again.") 
else { //Detailed check for valid date ranges 
    var monthfield = input.value.split("/")[0] 
    var dayfield = input.value.split("/")[1] 
    var yearfield = input.value.split("/")[2] 
    var dayobj = new Date(yearfield, monthfield - 1, dayfield) 
    if ((dayobj.getMonth() + 1 != monthfield) || (dayobj.getDate() != dayfield) || (dayobj.getFullYear() != yearfield)) 
     alert("Invalid Day, Month, or Year range detected. Please correct and submit again.") 
    else 
     returnval = true 
} 
if (returnval == false) input.select() 
return returnval 
} 

< /script> 

問題 如何使用JavaScript來驗證兩個領域。我試過& &但沒有工作。

<cfform action="someactionyoutake.cfm" method ="POST" onSubmit="return 
checkdate(document.formname.fieldx && document.formname.fieldy)"> 

在此先感謝

+2

請用代碼美化你粘貼代碼... HTTP之前://jsbeautifier.org/或在你的編輯器插件。 – 2014-09-29 07:47:01

+0

您應該保持一致:在JavaScript中,您編寫了'datecheck()',並在HTML中編寫了'checkdate()'。 另外,您不應該在HTML中使用*事件。 我不建議使用像'document.formname.fieldx'這樣的DOM Level 0訪問,而是使用document.getElementById(formOrElementId)。 'name'屬性已被棄用,順便說一句。 – laruiss 2014-09-29 07:55:40

+0

*我試過&&但沒有工作*您應該使用某種JavaScript調試器,如FF的Web控制檯,您可以幫助找到問題。 [邏輯'&&'操作符](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators?redirectlocale=en-US&redirectslug=JavaScript%2FGuide%2FExpressions_and_Operators#Logical_operators)用於比較布爾值,但是您傳遞的是DOM元素。因此錯誤。 – Leigh 2014-09-30 12:29:03

回答

1

只要改變

<cfform action="someactionyoutake.cfm" method ="POST" onSubmit="return datecheck(document.formname.fieldx && document.formname.fieldy)"> 

<cfform action="someactionyoutake.cfm" method ="POST" onSubmit="return datecheck(document.formname.fieldx) && datecheck(document.formname.fieldy)"> 
1

只是調用中間函數:

<script> 
    function checkForm(){ 
    return datecheck(document.formname.fieldx) && datecheck(document.formname.fieldy) 
    } 
</script> 
<cfform action="someactionyoutake.cfm" method ="POST" onSubmit="return checkForm()"> 
0

正如你所標記的問題與jQuery的試試下面的代碼片段

$(document).ready(function(){ 

var PreFormSubmitValidation = function (event) { 
     var isFormValid = true; 

     // your validation logic 
     if(<Validation Logic Fails>){ 
      isFormValid = false; 
     } 

    if(!isFormValid){ 
       return false; 
       // or can use 
       // event.preventDefault(); 
     } 
    }; 

$("#formId").submit(PreFormSubmitValidation); // calls the method when the form is posted to the server 
}); 

希望它幫助....