我有一个用户个人资料表单,其中包含 15 个文本字段、一些下拉列表和一个文本区域。该场景是用户可以在配置文件形式中输入字段。保存时无需填写所有字段,无论用户填写什么字段,我都必须通过 ajax 调用进行验证并保存在数据库中。
现在我正在使用这样的验证,
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;
}
可以看出,有很多嵌套的 if else 涉及到,这让我很恼火,需要一些更好的方法来做到这一点吗?有什么最好的选择吗?
最佳答案
您可以创建验证对象数组,每个对象包含属性 reg_ex
、field
、error_msg_container_id
和 error_msg
:
var validationRules = [
{ reg_ex: first_name,
field: ck_name,
error_msg_container_id: candidate_profile_error-first_name,
error_msg: "first name should only have alphabets" },
{ reg_ex: date_of_birth,
field: ck_date,
error_msg_container_id: candidate_profile_error-date_of_birth,
error_msg: "date of birth should be in YYYY-MM-DD format" }
];
在验证函数中,您只需迭代整个数组。这也使得维护您稍后可能添加的更多输入字段变得更加容易。
PS:如果您不知道如何迭代数组,请告诉我。
编辑:由于OP要求,迭代函数看起来类似于:
function isFormDataValid() {
for (i=0; i< validationRules.length; i++) {
// do the validation inside here, it will be repeated once for each validation rule;
}
return status;
}
如果您需要从数组中读取/写入变量属性名称,请使用此语法
Object[variable]
其中variable
包含您需要访问的属性名称的字符串。
var myObject = {
name: "peter",
age: 46
};
var validationRules = [ { fieldname: 'name'}, { fieldname: 'age' } ];
for (var i=0; i< validationRules.length; i++) {
alert(myObject[validationRules[i].fieldname]);
}
关于JavaScript 表单验证改进,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30411417/