如何验证在JavaScript中具有相同功能的所有字段? [英] How to validate all fields with the same function in JavaScript?
问题描述
我需要执行以下操作,但在Web上找不到任何类似表单验证的示例:
< script type =text / javascript>
函数something(){
如果调用此函数的字段上的值为== 2,4,6或8
alert(This number is invalid)
专注于这个领域。
< / script>
Field1调用something()
Field2调用something()
Field3调用something()
Field4调用something()
Field5调用something()
Field6调用了某些东西()
我尝试过这样:
函数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();
}
返回有效;
}
我调用这个函数:
a)一些文本< input type =textname =aasize =1maxlength =1onkeypress =return验证(AA)><峰; br>
但是这样我就不得不为每个字段创建一个不同的函数。那么我怎么能实现这一点?
您可以使用括号表示法而不是点当收集表单元素时,它允许你使用一个变量: 函数validate(field_name)
{
var valid = true;
var element = document.form [field_name];
if(!element)
{
alert('无法在您的表单中找到名为'+ field_name +'的字段!');
返回false;
}
var value = element.value;
if(value ==2|| value ==4|| value ==6|| value ==8)
{
警报(无效号码);
valid = false;
element.focus();
}
返回有效;
}
然后您可以调用 资源: I need to do the following, but I couldn't find any example of similar form validation on the web: I've tried like this: I'm calling the function like this: But this way I would have to create a different function for every field. So how could I implement this? You can use bracket notation instead of dot notation when collecting your form element, which allows you to use a variable: Then you'd just call Resources: 这篇关于如何验证在JavaScript中具有相同功能的所有字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! validate $
<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
with the name of the field you want to validate.