Jump to content

[SOLVED] JS validation


hassank1

Recommended Posts

I've many select boxes and textfields in my form

so I want to loop all selectbox and if they contain the value " ---select---" I want to show an alert (please fill all the fields)

 

and I want to loop all textfields and if one of them is empty I want to show an alert (please fill all the fields)

 

thanks..

Link to comment
https://forums.phpfreaks.com/topic/130619-solved-js-validation/
Share on other sites

To make things easy set the valueof select options with the text "---select---" to an empty value.

 

<html>
<head>
<script type="text/javascript">

var requiredFields = ['select1', 'select2', 'input1', 'input2'];

function validate_form(formObj)
{
    for (var i=0; i<requiredFields.length; i++)
    {
        if (!formObj[requiredFields[i]].value)
        {
            alert('Please fill all the fields.');
            return false;
        }
    }
    return true;
}


</script>
</head>

<body>

<form name="test" onsubmit="return validate_form(this)">
Select 1:
<select name="select1">
<option value="">---Select---</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select><br>

Select 2:
<select name="select2">
<option value="">---Select---</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select><br>

Input 1:
<input type="text" name="input1"><br>

Input 2:
<input type="text" name="input2"><br>

<br>
<button type="submit">Submit</button>
</body>
</html>

Link to comment
https://forums.phpfreaks.com/topic/130619-solved-js-validation/#findComment-677739
Share on other sites

in the requiredFields I put all the elements names in my form right?

 

Yes, some people would probably build the script to just programatically go through every field in the form, but that can create a problem when you decide to have a field that is not required.

Link to comment
https://forums.phpfreaks.com/topic/130619-solved-js-validation/#findComment-677929
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.