【问题标题】:Validate text-field and checkboxes in using JavaScript使用 JavaScript 验证文本字段和复选框
【发布时间】:2014-11-13 08:26:55
【问题描述】:

我正在尝试拥有一个完整的“验证表单”功能。我只缺少两件事:

  1. 将名称字段限制为仅限字母字符和空格
  2. 验证是否至少选择了一个复选框,并且最多允许 7 个复选框

这是我到目前为止所得到的......复选框验证似乎被绕过了,我不确定是不是因为我没有在“onSubmit”中调用函数......这就是我想要的原因有“一个”完整代码,

至于名称验证,我不确定如何将此代码放在 validateform3 函数中 或者至少将其与表单相关联,复选框验证也是如此。

名称验证 JS

function englishonly(inputtxt)
{   
    var letters = /^[A-Za-z]+$/;  
    if(inputtxt.value.match(letters))  
    {    
        return true;  
    }
    else  
    {  
        alert('Please type your name in english');  
        return false;  
    }  
} 

JAVASCRIPT

<script type="text/javascript">
    function validateForm3() {                      
        if (studentid.value == "")
        {
            studentid.style.borderColor = '#ff0000';
            alert("Please enter your Student ID");
            studentid.focus();
            return false;
        }

        var x=document.forms["form3"]["studentid"].value;
        if (! /^[0-9]{11}$/.test(x)) {
            studentid.style.borderColor = '#ff0000';
            studentid.style.backgroundColor = "#fdf0af";
            alert("The Student ID you entered is incorrect.");
            return false;
        }

        if (Email.value == "")
        {
            Email.style.borderColor = '#ff0000';
            alert("Please enter your e-mail");
            Email.focus();
            return false;
        }
        var x=document.forms["form3"]["Email"].value;
        if (x.indexOf("@")=== -1)
        {
            Email.style.borderColor = '#ff0000';
            Email.style.backgroundColor = "#fdf0af";
            alert("Please enter a valid email");
            return false;
        }

        if (Name.value == "")
        {
            Name.style.borderColor = '#ff0000';
            alert("Please enter your Name in English");
            Name.focus();
            return false;
        }                                       
    }
</script>

<script type="text/javascript">
    $(document).ready(function () {    
        $("#Regestir").click(function () {
            var numberOfChecked = $('input:checkbox:checked').length;
            // $.isNumeric( $("#studentid").val() )
            if( $("#studentid").val()!="" && $("#studentid").val()!="" && $("#Email").val()!="" &&  $("#Name").val()!="")
            {                                       
                if (numberOfChecked == 0 || numberOfChecked>7)
                {
                    alert("Only 7 courses are allowed.");
                    $("form").submit(function(e){
                        e.preventDefault();
                    });
                }
                else
                    $("form").unbind('submit').submit();
                    //$("#form3").submit();                
            }
            else 
            {
                alert ("You should enter all form values");
                $("form").submit(function(e){
                    e.preventDefault();
                });
            }
        });
    });
</script>

HTML

<form action="connect.php" method="get" id="form3" 
      name="form3" onsubmit="return validateForm3()">

【问题讨论】:

    标签: javascript jquery html validation checkbox


    【解决方案1】:

    要获得选中复选框的总数,请替换您的

    var numberOfChecked = $('input:checkbox:checked').length;
    

    var numberOfChecked = $('input:checkbox[name=type]:checked').length;
    

    关于你的名字验证englishonly函数的问题,你可以直接在你的validateform3函数中调用它。如果该函数的代码来自不同的文件,则必须包含该 js 文件。然后你的代码看起来像这样:

    function validateform3(){
        // ....
        var valid_english_name = englishonly($('#name')); // or whatever your 'name' input ID is
    }
    

    作为旁注,如果由于某些验证错误而想取消表单提交,您可以只使用e.preventDefault();return false; 而无需重新绑定submit 事件处理程序。

    此外,studentid.valueEmail.value 之类的代码可能不起作用。由于您使用的是jquery,您可以将它们替换为jquery selectors

    希望这会有所帮助。

    【讨论】:

    • 我尝试了您的建议,但没有成功,我仍然可以在不选择任何复选框的情况下提交表单,至于名称...我做了以下我在下面插入了名称脚本一个“单独的 js 标记”,并以与您建议它不起作用的方式相同的方式调用它,(我放置了正确的 ID 名称)......这是一个预览......(i.imgur.com/5RSr6NF.png)和(i.imgur.com/2PnxhG6.png
    • 更改为$('input:checkbox[name=type]:checked').lengthnumberOfChecked的值是多少?
    • 该值是一个变量,我使用一个数组来表示复选框 name="ckb[]" value="john"... name="ckb[]" value="edward"。 ...等
    • 尝试将console.log(numberOfChecked); 添加到您的代码中,并查看该变量在您的浏览器调试器中是什么。
    【解决方案2】:

    这里有一个FIDDLE 供您考虑。

    JS

    var inputname, length1, length2, checkboxcount = 0;
    $('.clickme').on('click', function () {
        inputname = $('.myname').val();
        length1 = inputname.length;
        length2 = inputname.replace(/[^a-zA-Z\s]/gi, '').length;
        if (length1 != length2)
           {
            $('#errorspan').append('Only letters are allowed in a name');
            validname = 0;
            }
        else
          {
           validname = 1;
           }
        $('.checkme').each(function(){
            if( $(this).is(':checked') )
            {
             checkboxcount = checkboxcount + 1;
            }
        });
        if(checkboxcount < 1)
        {
                 $('#errorspan').append('At least one checkbox must be checked');
                 validbox = 0;
        }
        else if(checkboxcount > 6)
        {
                 $('#errorspan').append('No more than 6 checkboxes can be checked');
                 validbox = 0;
        }
        else{
             validbox = 1;
        }
    
      if (validname === 1 && validbox == 1)
         {
          alert("Everything Valid");
          }
      else
        {
         alert("Not Valid! You have work to do!");
         }
    });
    

    【讨论】:

    • 谢谢! ,如果我为我的复选框使用数组怎么办?名称="ckb[]"
    • 什么意思?在我的小提琴中,不需要数组 - 它只查看页面上所有可用的复选框。你用这个数组做什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-12
    • 2011-11-11
    • 1970-01-01
    • 1970-01-01
    • 2012-01-20
    相关资源
    最近更新 更多