0

下面的验证码是交给我的,它看起来很重复。我如何从他的示例中学习如何减少下面正在验证的每个输入字段发生的重复过程......?我希望使用 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。

4

4 回答 4

2

检测代码中的哪些部分是重复的,以及哪些部分确实因字段而异。例如,您可以创建一个带有两个参数的函数:字段名称及其标签。

function validateRequiredField(name, label)
{
    var value = document.forms['subscribeForm'][name].value;
    if (value == null || value == '') {
        alert('Please enter your ' + label);
        document.forms['subscribeForm'][name].style.backgroundColor = 'yellow';
        return false;
    }
}

然后你可以调用这个函数,传递名称和标签作为参数:

validateRequiredField('First Name', 'first name');
validateRequiredField('ABC Link Relationship', 'relationship to ABC');
// ...

请记住,这些验证也应该在服务器端完成,因为有人可以禁用 JavaScript 并发送您的表单跳过您的客户端验证功能。

于 2013-10-25T21:34:28.120 回答
1

因为传递的唯一数据是对象和警报消息,而不是整个自定义函数,所以使用带有对象和消息参数的单个函数。

function isRequired(){
    required(document.forms['subscribeForm']['First Name'],'first name');
    required(document.forms['subscribeForm']['Last Name'],'last name');
    required(document.forms['subscribeForm']['State'],'state of residence');
    required(document.forms['subscribeForm']['Graduation Year'],'graduation year');
    required(document.forms['subscribeForm']['ABC Link Relationship'],'relationship to ABC');
    required(document.forms['subscribeForm']['Birthday'],'birthday');
}

function required(object,message){
    if (!obj) {
        alert('Please enter your '+message);
        obj.style.backgroundColor='yellow';
        return false;
    }
    return true;
}
于 2013-10-25T21:37:52.733 回答
0

首先,我建议使用 ID 来读取表单字段:

<input type="text" id="firstname" />

这允许您使用 jQuery('#firstname') 来选择此输入字段。

其次,这是我将如何完成使代码更小的任务:

你想在这里做什么?

  1. 您总是从表单中读取一些值(取决于各种 ID)。
  2. 然后检查该值是否为空。
  3. 如果未设置该值,您希望显示错误消息(再次取决于 ID)。
  4. 而且您还想标记丢失的字段,然后返回 false。

所以我会编写一个函数来做到这一点:

// function having a parameter for the ID and the custom error message
function checkFormField(fieldID, errorMsg) {

    // read value from field using jquery
    value = $(fieldID).value();

    // check for null or empty
    if (value == null || value == '') {

        // display custom error message
        alert(errorMsg);

        // change color of field using jQuery
        $(fieldID).css('background', 'yellow');

        return false;
    }
}

现在,您可以为要检查的每个字段重复使用此功能。新的 isRequired 方法如下所示:

function isRequired(){
    checkFormField('#firstname', 'Please enter your first name.');
    checkFormField('#lastname', 'Please enter your last name.');
    // and so on...
}
于 2013-10-25T21:43:45.670 回答
0

请注意,此示例需要可用作标识符的名称属性(无空格)

<input name="first_name" type="text" />
<input name="last_name" type="text" />

js:

function validateRequired(slug, field){
    // test for passing condition
    if (field.value !== null && field.value !== '') {
        return true;
    }
    else {
        alert('Please enter your ' + field.str);
    }
    return false;
}

/**
* Validate a form using a ruleset object
* 
*/
function validateFields(ruleset, form){
    var field = {};
    var errors = 0;

    // Loop though the ruleset
    for(var index in ruleset) { 
        // 
        if (ruleset.hasOwnProperty(index)) {
            field = ruleset[index];
            // check if input exists
            if (form[index]){
                field.value = form[index].value
            }
            if (ruleset[index].required) {
                if (!validateRequired(field)){
                    errors++;
                    field.invalid = true;
                }
            }
            // you could add more rules here...
        }
    }   
    return errors === 0;
}

var valid = validateFields({
    first_name : {
        required : true,
        str: 'first name'
    },
    last_name : {
        required : true,
        str: 'last name'
    }
    // ...
}, document.forms['subscribeForm']);
于 2013-10-25T22:45:37.487 回答