以下驗證代碼已交給我,它看起來如此重複。我如何從他的例子中學習如何減少每個輸入字段發生的重複過程,這些輸入字段在下面進行驗證....?我想用JavaScript更有效,而不是重複着同樣的功能和一遍又一遍,只是因爲一個形成一個新的輸入元素上添加了...壓縮驗證策略
function isRequired(){
firstNameRequired();
lastNameRequired();
stateRequired();
gradYearRequired();
relationshipRequired();
birthdayRequired();
}
function firstNameRequired(){
var firstName = document.forms['subscribeForm']['First Name'].value;
if (firstName == null || firstName ==''){
alert('Please enter your first name.');
document.subscribeForm.elements['First Name'].style.backgroundColor='yellow';
return false;
}
}
function lastNameRequired(){
var lastName = document.forms['subscribeForm']['Last Name'].value;
if (lastName == null || lastName ==''){
alert('Please enter your last name.');
document.subscribeForm.elements['Last Name'].style.backgroundColor='yellow';
return false;
}
}
function stateRequired(){
var state = document.forms['subscribeForm']['State'].value;
if (state == null || state ==''){
alert('Please enter your state of residence.');
document.subscribeForm.elements['State'].style.backgroundColor='yellow';
return false;
}
}
function gradYearRequired(){
var gradYear = document.forms['subscribeForm']['Graduation Year'].value;
if (gradYear == null || gradYear ==''){
alert('Please enter your graduation year.');
document.subscribeForm.elements['Graduation Year'].style.backgroundColor='yellow';
return false;
}
}
function relationshipRequired(){
var relationship = document.forms['subscribeForm']['ABC Link Relationship'].value;
if(relationship == null || relationship == ''){
alert('Please enter your relationship to ABC.');
document.subscribeForm.elements['ABC Link Relationship'].style.backgroundColor='yellow';
return false;
}
}
function birthdayRequired(){
var birthDay = document.forms['subscribeForm']['Birthdate'].value;
if(birthDay == null || birthDay == ''){
alert('Please enter your birthday.');
document.subscribeForm.elements['Birthdate'].style.backgroundColor='yellow';
return false;
}
}
...
<input type="submit" class="submitBtn" value="" onclick="isRequired()" />
另外,我有靈活性,如果需要在jQuery的工作是。
驗證應該在服務器端完成。 – bjb568
+1 Dude,我完全同意......我不知道爲什麼這家公司決定在前端留下驗證過程。有趣的是,驗證成功後,表單數據無論如何都會返回到它們的服務器。它只是擊敗了我爲什麼把這個表單驗證交給我們。所以爲了讓這個項目離開我的胸部,我只是想減少一些dup的混亂......至少爲了我的目的... :),並把它交給我的公關。 – blackhawk
我也想推薦[jQuery Validation](http://jqueryvalidation.org/),雖然它是你的本地JS示例(它需要jQuery)的側軌。它相當通用,易於實現並且用戶友好 - 而不是將錯誤消息顯示爲警報(難題:如果表單有多個錯誤會怎麼樣?),它會在每個「元素」下面顯示錯誤消息。 – Terry