0

我正在为我的 javascript 类制作一个表单,但我被困在其中的某个部分。我有一个单独的验证器 javascript 文件并在 html 文件上调用该函数。如果未填写表单区域,则所有验证都有效。我想要做的是,如果字段留空,它们将无法通过验证,并将在该字段中插入一个值。下面是表单字段、html 页面中的 javascript 函数和外部验证器 js 文件的示例。

在 html 头中调用函数:

function formvalidation(thisform) {
with (thisform) {
if (textbox_validation(first_name,"Please enter your first name.")==false)
{first_name.blur(); return false;};
if (textbox_validation(business_name,"Please enter your business. Please enter N/A if 
you do not have one.")==false) { business_name.focus(); return false; 
business_name.value=="N/A";};

外部 js 验证器:

function textbox_validation(entered, alertbox) {
with (entered) {
if (value==null || value=="") {
  alert(alertbox);
  return false;
}
else {
  return true;
   }
  }
}

所以验证器工作并专注于空字段,但对于我的一些字段,如果验证失败或未填充 int,我希望它们用某个值填充自己。business_name 代码行是我试图让它工作的时候。任何帮助深表感谢!

4

2 回答 2

0

使用 DOM 设置字段的占位符。像这样。

 var myInput = document.getElementById('input1');
 myInput.placeholder = 'This validation has failed.';
于 2013-08-21T16:12:50.457 回答
0

span通常,您不会使用 alert ,而是将错误消息div放在input. form此外(正如@Frits van Campen所提到的) ,使用 这样的尝试通常是不好的做法:with

function textbox_validation(entered, errormsg) {
    var errbox = document.getElementById(entered.id + '-errors'); // just to prevent writing it twice
    // Note this requires the input to have an id, and the errer box's id to be the same with an '-errors' suffix.

    // Instead of using with, just acces properties normally
    if (!entered.value) { // The `!` "neggation" operater makes "falsy" values `true`
                      // "falsy" values include `false`, the empty string, `0`, `null`, `undefined`, `NaN` and a few others
        // Put the error message in the DOM instead of alerting it
        errbox.innerHTML = errormsg;
        return false;
    }
    else {
        // Wipe any previous error messages
        errbox.innerHTML = '';
        return true;
    }
}

对于表单验证器,再次;让我们不要使用with. 但是,当尝试将“N/A”赋值给该值时,您使用了比较运算符而不是赋值运算符,并且您在返回后完成了它:

function formvalidation(thisform) {
    // just use the `!` "negation" operator
    if (!textbox_validation(thisform.first_name,
        "Please enter your first name."))
    {
        thisform.first_name.blur();
        return false;
    }
    if (!textbox_validation(business_name,
        "Please enter your business. Please enter N/A if you do not have one."))
    {
        thisform.business_name.focus();
        thisform.business_name.value = "N/A"; // for assignment, use `=`. `==` and `===` are used for comparison
        return false; // a return statement ends the function, make sure it's after anything you want to execute!
    }
}
于 2013-08-21T16:43:31.883 回答