我正在为我的javascript类做一个表单,而我却陷入了它的某个部分。我有一个单独的验证器javascript文件,并在html文件上调用该函数。如果未填写表单区域,则所有验证都有效。我想要做的是,如果字段留空,则验证将失败并将值插入该字段。下面是表单字段,html页面中的javascript函数和外部验证程序js文件的示例。
html head中的调用函数:
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代码行是我尝试使其工作的时候。非常感谢任何帮助!
答案 0 :(得分:0)
使用DOM设置字段的占位符。像这样。
var myInput = document.getElementById('input1');
myInput.placeholder = 'This validation has failed.';
答案 1 :(得分:0)
通常情况下,您不会使用提醒,而是将错误消息放在span
或div
附近input
或form
的顶部(或底部) {1}}。另外(如@Frits van Campen所述), generally bad practice to use 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!
}
}