以下验证码已交给我,它看起来非常重复。我如何从他的例子中学习如何减少下面验证的每个输入字段发生的重复过程....我想用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。
答案 0 :(得分: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并发送表单,跳过客户端验证功能。
答案 1 :(得分: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;
}
答案 2 :(得分:0)
首先,我建议使用ID来读取表单字段:
<input type="text" id="firstname" />
这允许您使用jQuery('#firstname')来选择此输入字段。
其次,这就是我如何开始缩小代码的任务:
你想在这做什么?
所以我编写了一个完全符合这个功能的函数:
// 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...
}
答案 3 :(得分: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']);