我需要做到以下几点,但我无法在网上找到类似表单验证的任何例子:
<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
您要验证的字段的名称。
资源:
function validate()
{
var valid = true;
var fields = ['list', 'of', 'unique', 'input', 'ids'];
for (inputid in fields) {
field = document.getElementById(inputid);
if ( field.value == "2" || field.value == "4" || field.value == "6" ||
field.value == "8" ) {
alert ( "Invalid number." );
valid = false;
field.focus();
break;
}
}
return valid;
}
您需要进行参数的功能,通过现场(或名称作为参数)。
我的示例使用的prototype.js函数$ F,但你可以在本地JavaScript与jQuery做的一样好或(更有点长,windedly)
function validate(field)
{
valid = true;
value = $F(field);
if ( value == "2" || value == "4" || value == "6" ||
value == "8" ){
alert ( "Invalid number." );
valid = false;
document.form.field_name.focus();
}
return valid;
}
validate('field1');
validate('field2');
等等
你可以尝试使用jQuery的 ,与这样的验证:
var valid = true;
$(".validateMe").each(function()
{
var v = this.value;
if(v == "2" || v=="4" || v=="6" || v=="8") {
valid = false;
// Exit for each
return false;
}
});
if(!valid){
alert("Invalid number.");
$(this).focus();
}
return valid;
每个字段必须有“validateMe”的CssClass
使用JavaScript
1.如果其他本网站上给出的语句都可以添加到您的验证功能的循环,检查形式的各个领域内。
http://eisabainyo.net/weblog/2009/04/30/10-examples-of-basic-input-validation-in-javascript/
2.还不清楚届时提及这个伟大指南
http://www.tizag.com/javascriptT/javascriptform.php
使用jQuery
你总是可以尝试jQuery验证插件
http://speckyboy.com/2010/06/22/50-jquery-plugins-for-form-functionality-validation-security-and-customisation/