我需要执行以下操作,但我在网络上找不到任何类似表单验证的示例:
<script type="text/javascript">
function something(){
if the value on the field who is calling this function == 2,4,6 or 8
alert("This number is invalid")
focus in this field.
</script>
Field1 call something()
Field2 call something()
Field3 call something()
Field4 call something()
Field5 call something()
Field6 call something()
我尝试过这样的:
function validate()
{
valid = true;
if ( document.form.field_name.value == "2" || document.form.field_name.value == "4" || document.form.field_name.value == "6" ||
document.form.field_name.value == "8" ){
alert ( "Invalid number." );
valid = false;
document.form.field_name.focus();
}
return valid;
}
我这样调用该函数:
a)"Some text" <input type="text" name="aa" size="1" maxlength="1" onkeypress="return validate(aa)"><br>
但是这样我就必须为每个字段创建一个不同的函数。那么我该如何实现呢?
最佳答案
在收集表单元素时,您可以使用括号表示法而不是点表示法,这样您就可以使用变量:
function validate(field_name)
{
var valid = true;
var element = document.form[field_name];
if (!element)
{
alert('A field named ' + field_name + ' cannot be found in your form!');
return false;
}
var value = element.value;
if (value == "2" || value == "4" || value == "6" || value == "8")
{
alert("Invalid number.");
valid = false;
element.focus();
}
return valid;
}
然后您只需使用要验证的字段名称调用 validate
即可。
资源:
关于php - 如何在 JavaScript 中使用相同的函数验证所有字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3752139/