How to fix this Javascript Form Validation script? - javascript

I am using the following javascript for form validation:
<script type="text/javascript">
function validate_form ( )
{
valid = true;
if ( document.contact_form.contact_name.value == "" )
{
alert ( "Please fill in the 'Your Name' box." );
valid = false;
}
if ( ( document.contact_form.gender[0].checked == false ) && ( document.contact_form.gender[1].checked == false ) )
{
alert ( "Please choose your Gender: Male or Female" );
valid = false;
}
if ( document.contact_form.age.selectedIndex == 0 )
{
alert ( "Please select your Age." );
valid = false;
}
if ( document.contact_form.terms.checked == false )
{
alert ( "Please check the Terms & Conditions box." );
valid = false;
}
return valid;
}
</script>
The form:
<form name="contact_form" method="post" action="somepage.php" onSubmit="return validate_form();">
<h1>Please Enter Your Details Below</h1>
<p>Your Name: <input type="text" name="contact_name"></p>
<p>Your Gender: <input type="radio" name="gender" value="Male"> Male
<input type="radio" name="gender" value="Female"> Female</p>
<p>Your Age:
<select name="age">
<option value="">Please Select an Option:</option>
<option value="0-18 years">0-18 years</option>
<option value="18-30 years">18-30 years</option>
<option value="30-45 years">30-45 years</option>
<option value="45-60 years">45-60 years</option>
<option value="60+ years">60+ years</option>
</select>
<p>Do you agree to the Terms and Conditions?
<input type="checkbox" name="terms" value="Yes"> Yes
<p><input type="submit" name="send" value="Send Details"></p>
</form>
The validation works fine, except it displays one alert box after another to point out which fields haven't been filled in or selected.
How can this script be modified so that all the missing fields are pointed out in ONE alert box like:
Please fill in the following fields:
Name, Gender, Age, Terms and
Conditions

Use a string or an array (as in the example below) to accumulate the error fields then generate the alert statement and return value based on its contents. For example:
function validate_form () {
var invalid=[], form=document.contact_form;
if (form.contact_name.value == "") {
invalid.push('Name');
}
if ((form.gender[0].checked == false) && (form.gender[1].checked == false)) {
invalid.push('Gender');
}
if (form.age.selectedIndex == 0) {
invalid.push('Age');
}
if (form.terms.checked == false) {
invalid.push('Terms and Conditions');
}
if (invalid.length > 0) {
alert('Please fill in the following fields: ' + invalid.join(', ') + '.');
return false;
}
return true;
}

function validate_form ( )
{
valid = true;
var myArray= new Array();
if ( document.contact_form.contact_name.value == "" )
{
myArray.push('Name');
valid = false;
}
if ( ( document.contact_form.gender[0].checked == false ) && ( document.contact_form.gender[1].checked == false ) )
{
myArray.push('Gender');
valid = false;
}
if ( document.contact_form.age.selectedIndex == 0 )
{
myArray.push('Age');
valid = false;
}
if ( document.contact_form.terms.checked == false )
{
myArray.push('Term & Conditions');
valid = false;
}
if (valid==false)
alert ( "Please fill in the following fields: "+myArray);
return valid;
}
Simple one
function validate_form ( )
{
var myArray= new Array();
if ( document.contact_form.contact_name.value == "" )
myArray.push('Name');
if ( ( document.contact_form.gender[0].checked == false ) && ( document.contact_form.gender[1].checked == false ) )
myArray.push('Gender');
if ( document.contact_form.age.selectedIndex == 0 )
myArray.push('Age');
if ( document.contact_form.terms.checked == false )
myArray.push('Term & Conditions');
if (myArray.length>=0){
alert ( "Please fill in the following fields: "+myArray);
return false;
}
return true;
}

You shouldn't really rely on document.form.Foo syntax, rather, give the elements id's and use getElementById to select them. Anyway"
function validate_form(){
var valid = true,
errors = [];
if (document.contact_form.contact_name.value == "") {
error.push("Please fill in the 'Your Name' box.");
valid = false;
}
if ((document.contact_form.gender[0].checked == false) && (document.contact_form.gender[1].checked == false)) {
errors.push("Please choose your Gender: Male or Female");
valid = false;
}
if (document.contact_form.age.selectedIndex == 0) {
errors.push("Please select your Age.");
valid = false;
}
if (document.contact_form.terms.checked == false) {
errors.push("Please check the Terms & Conditions box.");
valid = false;
}
if(errors.length > 0){
alert('Errors:\n' + errors.join('\n'));
}
return valid;
}

Better to go for jQuery validation plugin. It easy, flexible, straight forward and very fast to implement.
Otherwise use #Evan suggested technique.

Related

Trying to convert this big if else statement into a loop

Hi I'm trying to make this code more clean. I struggle with arrays and loops and have no idea how to convert this into into a loop. This is javascript for a form on an html page and if they leave a field blank, when they hit submit it should return an alert box and if everything is submitted properly it should confirm with them. There's also a reg exp for an acceptable postal code entry.
function validate()
{
var register = document.forms[0];
if (register.fname.value === "")
{
alert("Please fill out your first name.");
return false;
}
else if(register.lname.value === "")
{
alert("Please fill out your last name.");
return false;
}
else if(register.address.value === "")
{
alert("Please fill out your address.");
return false;
}
else if(register.postal.value ==="")
{
alert("Please enter a valid postal code.");
return false;
}
else if(!checkPostal(register.postal.value))
{
alert("Please enter a valid postal code.");
return false;
}
else if(register.eAddress.value === "")
{
alert("Please fill out your email address.");
return false;
}
return confirm("Is the information correct?");
}
//postal code regExp
function checkPostal()
{
var myReg = /^[A-Z]\d[A-Z] ?\d[A-Z]\d$/ig;
return myReg.test(document.getElementById("postal").value);
}
You can make this a pure HTML solution if you want to reduce javascript:
inputs have a required attr ref
additionally, inputs have a pattern attr ref that supports regex.
This kind of solution lets the browser handle feedback
<form>
<label>first name:
<input type="text" name="fname" required
minlength="1">
</label><br/>
<label>last name:
<input type="text" name="lname" required
minlength="1">
</label><br/>
<label>postal code:
<input type="text" name="zip" required pattern="^[A-Z]\d[A-Z] ?\d[A-Z]\d$"
minlength="1">
</label><br/>
<input type="submit" />
</form>
$.each( $( "#input input" ), function( key, element ) {
if( !$(element).val() ) {
$( "#error" + key ).text( "Input " + $( element ).attr( "name" ) + " is required");
return false;
}
});
Set your message as attribute on each element of the form like this:
<form method="POST" action="submit.php">
<input id="item1" type="text" value="" data-message="My error message" data-must="true">
...//do the same for other elements...
</form>
Now loop like below
var elements = document.forms[0].elements;
for (var i = 0, element; element = elements[i++];) {
if (element.getAttribute("must") && element.value === ""){
alert(element.getAttribute("message"));
return false;
}
}
return confirm("Is the information correct?");

JavaScript input type validation

I can't seem to figure out the proper JavaScript to validate this form. Please help/provide feedback!
Essentially, my script should validate whether the user has entered data in the input text box, has checked a radio button, has checked at least one checkbox, and has selected an option from the select items.
Also the form uses a submit button to invoke the validation script, so that the form is processed only when the form fields are validated and accepted. If a field is invalid then display a message to the user.
Also need to make sure the form doesn't automatically reset every time the user gets a validation error.
<body>
<section>
<h1 style="text-align: center">Vacation Interest Vote Form</h1>
<form name="VacayForm" action="mailto:" onsubmit="return Validate1()" method="post">
<p>Name:<input type="text" name="name" size="25"></p><br>
<p>Do You Prefer an international destination?</p>
<p>Domestic<input type="radio" name="domint" value="domestic"></p>
<p>International<input type="radio" name="domint" value="international"></
<br>
<p>Where would you like to go?</p>
<select type="text" name="continent" value="select" size="1">
<option value="domestic">Domestic</option>
<option value="europe">Europe</option>
<option value="camerica">Central America</option>
<option value="asia">Asia</option>
<option value="aus">Australia</option>
</select>
<br>
<p>Check the box to act as your digital signature to cast your vote
<input type="checkbox" value="agree" name="sig">
<input type="submit" value="Send" name="submit" onclick="if(!this.form.sig.checked){alert('You must agree to cast your vote by checking the box.');
return false}">
<input type="reset" value="Reset"name="reset">
</form>
</section>
<script>
function Validate1() {
var nam = document.forms["VacayForm"]["name"];
var dom = document.forms["VacayForm"]["domestic"];
var int = document.forms["VacayForm"]["international"];
var sel = document.forms["VacayForm"]["select"];
var agree = document.forms["VacayForm"]["agree"];
//if (name.value == "")
//{
// window.alert("Please enter your name.");
// name.focus();
// return false;
//}
if( document.VacayForm.name.value == "" )
{
alert( "Please provide your name!" );
document.VacayForm.name.focus() ;
return false;
}
if (domestic.value == "")
else (international.value == "")
{
window.alert("Please select domestic or international preference to proceed.");
domestic.focus();
international.focus();
return false;
}
if (select.selectedIndex < 1)
{
alert("Please select where you prefer to visit");
select.focus();
return false;
}
return true;
}
//function Validate2() {
// var radios = document.getElementsByName("yesno");
// var formValid = false;
// var i = 0;
// while (!formValid && i < radios.length) {
// if (radios[i].checked) formValid = true;
// i++;
// }
// if (!formValid) alert("Must check an option!");
// return formValid;
//}
</script>
</body>
</html>
Your validate function could look like this...
function validate() {
var form = document.forms.VacayForm;
var name = form.name;
var domInt = form.domint;
var continent = form.continent;
var agree = form.agree;
if (!name.value) {
alert( "Please provide your name!" );
name.focus();
return false;
}
if (!domInt.value) {
alert( "Please select domestic or international preference to proceed" );
domInt.focus();
return false;
}
if (!continent.value) {
alert("Please select where you prefer to visit");
continent.focus();
return false;
}
if (!agree.checked) {
alert("Please check agree to continue");
agree.focus();
return false;
}
return true;
}
This article from Javascript.info website teaches how to use forms and form elements...

Common javascript form validation not working

I've been trying to use the following javascript code to validate several fields on a contact form. The validation works for the first item being validated, the name field, but not the second, the email field. If the name field is filled in, the validation seems to skip over the email field check when it's blank and the form submits.
function validateForm()
{
var n = document.contact.name.value;
n = n.trim();
var ema = document.contact.email.value;
ema = ema.trim();
//Check if the name is missing
if (n == null || n == "" || empty(n))
{
alert("Please enter your name.");
document.contact.name.focus();
return false;
}
//Check if the email is missing
else if ( ema == null || ema == "" || empty(ema) )
{
alert( "Please enter your email address." );
document.contact.email.focus();
return false;
}
else
{
return( true );
}
}
Here is the HTML on the contact form:
<FORM name="contact" METHOD="POST" ACTION="thankyou.php" onsubmit="return validateForm()">
<input type="checkbox" name="newsletter" value="YES" width="30" height="30"> Check the box to subscribe to Herb's Newsletter
<input type="text" class="form-control" size=20 name="name" placeholder="Your name" />
<input type="email" class="form-control" name="email" placeholder="Email Address" />
<input class="btn btn-theme btn-subscribe" type="submit" value="Send" />
</form>
Thank you
You seem to be using empty function in your if clauses which doesn't seem to be defined nor it is part of the standard javascript functions. Try getting rid of it:
function validateForm() {
var n = document.contact.name.value;
n = n.trim();
var ema = document.contact.email.value;
ema = ema.trim();
//Check if the name is missing
if (n == null || n == "") {
alert("Please enter your name.");
document.contact.name.focus();
return false;
} else if (ema == null || ema == "") {
//Check if the email is missing
alert( "Please enter your email address." );
document.contact.email.focus();
return false;
} else {
return true;
}
}
And here's a live demo.
In your code you use else if statement.
Basically what you code does is:
check name -> if that is falsy check email -> if that is falsy move into else condition.
But when the name is true, the if statement will not move to else conditions because it it already satisfied. So if you want to check both, you either separate the statements and make a 5 separate ifs, make it a switch statement or you create one long check. For example:
if ((n == null || n == "" || empty(n)) || ( ema == null || ema == "" || empty(ema) ))
{
alert("Something is missing");
return false;
}
else
{
return( true );
}
or you use multiple ifs:
function validateForm() {
var n = document.contact.name.value;
n = n.trim();
var ema = document.contact.email.value;
ema = ema.trim();
//Check if the name is missing
if (n == null || n == "" || empty(n))
{
alert("Please enter your name.");
document.contact.name.focus();
return false;
}
//Check if the email is missing
if ( ema == null || ema == "" || empty(ema) )
{
alert( "Please enter your email address." );
document.contact.email.focus();
return false;
}
return( true );
}
The latter will always return true unless one of the if statements is triggered.
And see answer below about the empty() thing. I don't know what that is and if it messes anything up.

Javascript Validation for all field with Required attribute

I've searched high and low for the answer to this but can't find it anywhere.
I have a form which has the HTML 'required' attributes and it does a fine job of highlighting the fields that need to filled in before submission...or would do, but the system which my form is bolted onto (of which I have no control over) submits the form anyway after a few seconds. It relies on Javascript for it's submission. Therefore I'd like to write a Javascript script to check all fields for a required attribute. Currently I have a script that specifies the fields I want to be mandatory, but if it could look up the attribute instead, that would be brilliant.
In case that input[type=submit] is used, you don't need any JavaScript
<form id="theForm" method="post" acion="">
<input type="firstname" value="" required />
<input type="lastname" value="" required />
<input type="submit" name="submit" value="Submit" />
</form>
Working jsBin
But if input[type=button] is used for submitting the form, use the snippet below
<form id="theForm" method="post" acion="">
<input type="firstname" value="" required />
<input type="lastname" value="" required />
<input type="button" name="button" value="Submit" />
</form>
window.onload = function () {
var form = document.getElementById('theForm');
form.button.onclick = function (){
for(var i=0; i < form.elements.length; i++){
if(form.elements[i].value === '' && form.elements[i].hasAttribute('required')){
alert('There are some required fields!');
return false;
}
}
form.submit();
};
};
Wotking jsBin
Many years later, here is a solution that uses some more modern Javascript:
for (const el of document.getElementById('form').querySelectorAll("[required]")) {
if (!el.reportValidity()) {
return;
}
}
See Vlad's comment for a link to the Constraint Validation API (thanks Vlad, that helped!)
You can use Constraint validation API, which is supported by most browsers.
I'm late to the party but this worked for me.
<input type="firstname" value="" required />
document.getElementById('theForm').reportValidity();
if (check) {
//success code here
return true;
}
Credit to Vlad and a.l.e for pointing me in the right direction with their previous answers. This is a simplified version of their approach.
this will be validating all your form field types
$('#submitbutton').click(function (e) {
e.preventDefault();
var form = document.getElementById("myForm");
var inputs = form.getElementsByTagName("input"), input = null, select = null, not_pass = false;
var selects = form.getElementsByTagName("select");
for(var i = 0, len = inputs.length; i < len; i++) {
input = inputs[i];
if(input.type == "hidden") {
continue;
}
if(input.type == "radio" && !input.checked) {
not_pass = true;
}
if(input.type == "radio" && input.checked){
not_pass = false;
break;
}
if(input.type == "text" && !input.value) {
not_pass = true;
}
if(input.type == "text" && input.value){
not_pass = false;
break;
}
if(input.type == "number" && !input.value) {
not_pass = true;
}
if(input.type == "number" && input.value){
not_pass = false;
break;
}
if(input.type == "email" && !input.value) {
not_pass = true;
}
if(input.type == "email" && input.value){
not_pass = false;
break;
}
if(input.type == "checkbox" && !input.checked) {
not_pass = true;
}
if(input.type == "checkbox" && input.checked) {
not_pass = false;
break;
}
}
for(var i = 0, len = selects.length; i < len; i++) {
select = selects[i];
if(!select.value) {
not_pass = true;
break;
}
}
if (not_pass) {
$("#req-message").show();//this div # in your form
return false;
} else {
//do something here
}
});
If using either the simple "required" solution above or the "Constraint Validation API" solution, how do you make a select option required if it is contingent on another select field having a certain answer. I used the "required" method as you can see below which works great for Country select.
<select id="country_code" name="country_code" required>
<option value="">--None--</option>
<option value="AL">Albania</option>
<option value="US">United States</option>
</select>
<script>
$("select[name='country_code']").change(function() {
if ($(this).val() == "US") {
$("select[name='state_code'] option").removeClass('hidden');
$("select[name='state_code'] option").addClass('required');
} else {
} else {
$("select[name='state_code'] option").addClass('hidden');
}
});
</script>
<label for="state_code">State/Province</label>
<select id="state_code" name="state_code">
<option value="">--None--</option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
</select>
As you can see, I tried adding the class "required" to State select if Country select is US, but it didn't do anything.

How can I validate form client-side with this naming convention

I have a form that has some simple javascript to validate a simple questionnaire. It used the name attribute on inputs in the form but now the page is integrated with the clients CMS it needs to use a particular naming convention which I can't get to work.
The old form had inputs like this:
<input type="text" name="firstName" />
but with the cms all fields require "fields[firstName]", e.g.:
<input name="fields[first-name]">
How do I get this to work.
Exisiting JS below:
function validate_form ( )
{
valid = true;
if ( ( document.register.question[0].checked == false ) && ( document.register.question[1].checked == false ) && ( document.register.question[2].checked == false ) )
{
alert ( "Please choose an answer" );
valid = false;
}
else if ( document.register.form_title.value == "" )
{
alert ( "Please fill in the 'Title' box." );
valid = false;
}
else if ( document.register.fName.value == "" )
{
alert ( "Please add your First Name" );
valid = false;
}
else if ( document.register.lName.value == "" )
{
alert ( "Please add your Last Name" );
valid = false;
}
else if ( document.register.email.value == "" )
{
alert ( "Please add a valid email address" );
valid = false;
}
else if ( document.register.country.selectedIndex == 0 )
{
alert ( "Please select your Country" );
valid = false;
}
else if ( document.register.dob1.selectedIndex == 0 )
{
alert ( "Please ensure your date of birth is complete" );
valid = false;
}
else if ( document.register.dob2.selectedIndex == 0 )
{
alert ( "Please ensure your date of birth is complete" );
valid = false;
}
else if ( document.register.dob3.selectedIndex == 0 )
{
alert ( "Please ensure your date of birth is complete" );
valid = false;
}
else if ( document.register.terms.checked == false )
{
alert ( "Please check the Terms & Conditions box." );
valid = false;
}
return valid;
}
you can use jquery with something like this:
$("input[name=fields\\[first-name\\]]").val()

Categories