Purple Owl
Purple Owl

Reputation: 137

Validate 2 check boxes and 2 text boxes and a date format

My goal is to check if user enter/choose at least one option. If he does not, an alert will appear.

If the user enter a date, there will be a validation.

Right now, when user does NOT enter date BUT choose other option, the alert message of date validation still appear.

http://jsfiddle.net/N43vg/1/

OR

Below are my codes...

Help will be appreciate.. Thanks! :)

var radio1 = document.getElementById('pending').checked;
    var radio2 = document.getElementById('completed').checked;

    var on = document.forms["searchform"]["order"].value;
    var date = document.forms["searchform"]["date"].value;

    if ((radio1 == "") && (radio2 == "") && (on == null || on=="") && (date == null || date =="")){
        alert('Please Choose at least 1 Option');
        return false;
    }



    if (date != null || date != "")
    {
         var pattern = /^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$/;
        if(!(pattern.test(date)))
        {
            alert("Please enter the correct date format DD/MM/YYYY");
        return false;
        }

Upvotes: 1

Views: 99

Answers (1)

for your radio1 and radio2 to validate if eaither of the radios are check you need to write your code like so: if ((!radio1) && (!radio2){}, because the values in radio1 and radio2 will be true or false, and not a string value.

I would write the entire script like the code below, the null check is not necessary.

if ((!radio1) && (!radio2) && (on ==="") && (date ==="")){
    alert('Please Choose at least 1 Option');
    return false;
}



if (date !== "")
{
     var pattern = /^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$/;
    if(!(pattern.test(date)))
    {
        alert("Please enter the correct date format DD/MM/YYYY");
    return false;
    }

Upvotes: 3

Related Questions