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

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()

Related

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 form validation (decimal places) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am using the following script to validate a form and would like to be able to to ensure that the inputter correctly inputs a numeric value with decimal places on the last field (amount).
Can anyone help with this?
<script type="text/javascript">
<!--
function validate()
{
if( document.create_invoice.job_no.value == "" )
{
alert( "Please provide a Job No" );
document.create_invoice.job_no.focus() ;
return false;
}
if( document.create_invoice.contact.value == "-1" )
{
alert( "Please provide a Customer Contact" );
return false;
}
if( document.create_invoice.employee.value == "-1" )
{
alert( "Please provide an Employee" );
return false;
}
if( document.create_invoice.invoice_no.value == "" )
{
alert( "Please provide an Invoice No" );
document.create_invoice.invoice_no.focus() ;
return false;
}
if( document.create_invoice.address.value == "" )
{
alert( "Please provide an Address" );
document.create_invoice.address.focus() ;
return false;
}
if( document.create_invoice.amount.value == "" )
{
alert( "Please provide an Amount" );
document.create_invoice.amount.focus() ;
return false;
}
}
//-->
</script>
Thanks,
John
You might want to use parseFloat() for that... Try :
if( parseFloat(document.create_invoice.amount.value) != document.create_invoice.amount.value )
{
alert( "Please provide a decimal value" );
document.create_invoice.amount.focus() ;
return false;
}
That might just do the trick for you.

jquery problems in IE6, anyone?

function validate_request_form(){
var valid = true;
if ( document.request_form.firstname.value == "" )
{ alert ( "Please fill in first name" ); valid = false; return false; }
return valid;
}
$j('#video-request-form').submit(function() {
if (!validate_request_form() )
return false;
});
I am using this code to validate my form. My form has id=video-request-form and the form name is request_form. This all works fine in latest FF, but can't get it to work in IE6...anyone?
I suggest utilizing jQuery more instead of native JS. They are they to help. Try the following:
function validate_request_form(){
var valid = true;
if ( $j('#firstname').val() == "" ) {
alert ( "Please fill in first name" ); valid = false; return false;
}
return valid;
}
This assumes the field has an ID of firstname

jQuery form validation issue

I'm not using any jQuery plugin to validate the form, just plain jQuery. My issue is that after it validates all the input elements, even if it shows the error message to the user, it will still submit the form without the user correcting the error.
To elaborate, my form has 3 input elements. with jQuery validation, if all the 3 elements are empty, and the user clicks on the Submit button, it will throw an error highlighting the first element. If the user does not correct the error, but clicks on the submit button again, it will highlight the second element [with the first input element still highlighted]. Likewise for the 3rd element. Now if the user without correcting the error (that is, the input elements are still highlighted) clicks on the submit button again, it will submit the form. Ideally, it should keep on highlighting the first input element till the user corrects his error and then validate the 2nd input element and so on. .and this is what I want to do.
jQuery code:
$(function() {
/*Form Validation*/
$("#name")
.focus(function() {
if ($(this).val() == "Your Name" || $(this).val() == "Field cannot be blank" ) {
$(this).val("");
$(this).css("background", "#FFF");
}
})
.blur(function(){
if ($(this).val() == "") {
$(this).val("Your Name");
}
})
.keyup(function() {
$("#name").val($(this).val());
}),
$("#email")
.focus(function() {
if ($(this).val() == "Your Email" || $(this).val() == "Field cannot be blank" ) {
$(this).val("");
$(this).css("background", "#FFF");
}
})
.blur(function(){
if ($(this).val() == "") {
$(this).val("Your Email");
}
})
.keyup(function() {
$("#email").val($(this).val());
}),
$("#msg")
.focus(function() {
if ($(this).val() == "Your Message" || $(this).val() == "You forgot to enter your message" ) {
$(this).val("");
$(this).css("background", "#FFF");
}
})
.blur(function(){
if ($(this).val() == "") {
$(this).val("Your Message");
}
})
.keyup(function() {
$("#msg").val($(this).val());
})
});
function checkForm(form) {
var cssObj = {
'background-color' : 'red',
'border' : 'green'
}
if ($("#name").val() == "" || $("#name").val() == "Your Name") {
$("#name").css(cssObj);
$("#name").val('Field cannot be blank');
return false;
}
else if ($("#email").val() == "" || $("#email").val() == "Your Email") {
$("#email").css(cssObj);
$("#email").val('Field cannot be blank');
return false;
}
else if ($("#msg").val() == "" || $("#msg").val() == "Your Message") {
$("#msg").css(cssObj);
$("#msg").val('You forgot to enter your message');
return false;
}
else {
return true;
}
}
. .html:
<form action="somepage.php" method="post" id="contactform">
<div class="container">
<div class="field">
<input type="text" tabindex="1" value="Your Name" name="name" id="name" /><br />
</div>
<div class="field">
<input type="text" tabindex="2" value="Your Email" name="name" id="email" /><br />
</div>
<div class="field">
<textarea tabindex="3" name="msg" id="msg">Your Message</textarea><br />
</div>
<input type="button" onclick="return checkForm('contactform');" id="sb" value="Submit" class="submitbtn" />
</div>
</form>
Your checkform function behaves like it should.
However here is a possible correction
function checkForm(form) {
var cssObj = {
'background-color' : 'red',
'border' : 'green'
}
if ($("#name").val() == "" || $("#name").val() == "Your Name" || $("#name").val() == 'Field cannot be blank' ) {
$("#name").css(cssObj);
$("#name").val('Field cannot be blank');
return false;
}
else if ($("#email").val() == "" || $("#email").val() == "Your Email" || $("#email").val() = 'Field cannot be blank' ) {
$("#email").css(cssObj);
$("#email").val('Field cannot be blank');
return false;
}
else if ($("#msg").val() == "" || $("#msg").val() == "Your Message" || $("#msg").val() == 'You forgot to enter your message' ) {
$("#msg").css(cssObj);
$("#msg").val('You forgot to enter your message');
return false;
}
else {
return true;
}
}
Please look at http://en.wikipedia.org/wiki/Idempotence too.

How to fix this Javascript Form Validation script?

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.

Categories