简体   繁体   中英

Validate text-field and checkboxes in using JavaScript

I'm trying to have a full "validate-form" function. I'm only missing two things:

  1. To restrict the Name field to alphabetical characters only and white spaces
  2. To validate that at least one checkbox is selected and a maximum of 7 checkboxes are allowed

Here's what I got so far ... The checkbox validation seems to get bypassed and I'm not sure if it's because I'm not calling the function in the "onSubmit" .... this is why I want to have "one" full code,

As for the Name Validation , I'm not sure how to place this code within the validateform3 function or at least relate it to the form , same goes for the checkbox validation.

NAME VALIDATION 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()">

To get the total number of checked checkboxes, replace your

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

with

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

As for your question on your name validation englishonly function, you can just call it directly in your validateform3 function. If the codes for that function come from a different file, you will have to include that js file. Then your codes can look something like this:

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

As a sidenote, if you want to cancel the form submission due to some validation errors, you can use just e.preventDefault(); or return false; without the re-binding the submit event handler.

In addition, codes like studentid.value and Email.value will probably not work. Since you are using jquery, you can replace them with jquery selectors .

Hope this helps.

Here's a FIDDLE for you to think about.

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!");
     }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM