我有一個用戶配置文件表單,包含15個文本字段以及一些下拉菜單和一個textarea。場景是用戶可以以簡介形式輸入字段。在保存時,不必填寫所有字段,無論用戶填寫什麼字段,都必須通過ajax調用驗證並保存在數據庫中。JavaScript表單驗證改進
現在我使用驗證這個樣子,
var first_name = document.getElementById('id_candidate_profile-first_name').value;
....
var status = false;
if(first_name != ''){
status = regex_test(first_name, ck_name);
if(status==false){
document.getElementById('candidate_profile_error-first_name').innerHTML = "first name should only have alphabets";
}
else{
status = true;
}
}
if(middle_name != "" & status = true){
status = regex_test(middle_name, ck_name);
if(status==false){
document.getElementById('candidate_profile_error-middle_name').innerHTML = "middle name should only have alphabets";
}
else{
status = true;
}
}
if (last_name != '' & status = true){
status = regex_test(last_name, ck_name);
if(status==false){
document.getElementById('candidate_profile_error-last_name').innerHTML ="last name should only have alphabets";
}
else{
status = true;
}
}
if (date_of_birth != '' & status = true){
status = regex_test(date_of_birth, ck_date);
if(status==false){
document.getElementById('candidate_profile_error-date_of_birth').innerHTML ="date of birth should be in YYYY-MM-DD format";
}
else{
status = true;
}
}
if (birth_place != '' & status = true){
status = regex_test(birth_place, ck_name);
if(status==false){
document.getElementById('candidate_profile_error-birth_place').innerHTML ="birth_place should only have alphabets";
}
else{
status = true;
}
}
if (nic != '' & status = true){
status = regex_test(nic, ck_name);
if(status==false){
document.getElementById('candidate_profile_error-nic').innerHTML ="nic should be in this format 12345-1234567-1";
}
else{
status = true;
}
}
if (status = true) {
// made ajax call
}
function regex_test(variable, regex){
var _result = false;
if(!regex.test(variable)){
_result = false;
}
else {
_result = true;
}
return _result;
}
可以看出,有很多的嵌套,如果其他人蔘與這激怒我,需要一些更好的方法來做到這一點?任何最好的選擇?
對於首發我會強烈建議您適當的打算你的代碼。它會盡可能幫助你的挫折,因爲它會幫助我們幫助你。 – Wtower