1

I'm trying to validate a form using JavaScript but i'm a bit stuck on displaying a message next to the field to say that "This field is required". How do I go about doing this? Sorry, I'm very new to JavaScript. Here's my js code:

var allFieldsRequired = true;
function specialPostcode(postalCode)
{
    var re = /^[TA]{2}([1-14]|22|15){1,2}/;
    if(re.test(postalCode))
    {
        alert("You have been entered into a competition to win special prize!!");
    }

}

function validatePostcode(postalCode)
{
    var re = /^[A-Z]{2}\d{1,2}\s\d{1}[A-Z]{2}$/;
    if(!re.test(postalCode))
    {
        alert('Postcode is not valid');
    }
    return re.test(postalCode);
}

function validateCard(promoCardNumber)
{
    var re = /^[A-Z]{1}([A-Z]|\d){4}\s?([A-Z]|\d){5}\s?([A-Z]|\d){3}\d{1}$/;
    if(!re.test(promoCardNumber))
    {
        alert('Promotional card number is not valid');
    }
    return re.test(promoCardNumber);
}

function validate(val)
{
    if(val == "")
    {
        return false;
    }
    else
    {
        return true;
    }
}

function verification(orderForm)
{
//set boolean flag
var valid = true;
if(allFieldsRequired)
{
    // validations
    if(valid)
    {
        valid = validatePostcode(orderForm.postalCode.value);
    }
    if(valid)
    {
        valid = validateCard(orderForm.promoCardNumber.value);
    }
    if(valid)
    {
        valid = validate(orderForm.firstName.value);
    }
    if(valid)
    {
        valid = validate(orderForm.surname.value);
    }
    if(valid)
    {
        valid = validate(orderForm.phoneNumber.value);
              }
    if(valid)
    {
        valid = validate(orderForm.streetName.value);
    }
    if(valid)
    {
        valid = validate(orderForm.city.value);
              }                                                          
    if(valid)
    {
        valid = validate(orderForm.billEmailAddress.value);
    }
    if(valid)
    {
        valid = validate(orderForm.billPhoneNumber.value);
    }
    if(valid)
    {
        valid = validate(orderForm.billCardNumber.value);
    }
    if(valid)
    {
        specialPostcode(orderForm.postalCode.value);
    }

}
else
{
    // validations
    if(valid)
    {
        valid = validatePostcode(orderForm.postalCode.value);
    }
    if(valid)
    {
        valid = validateCard(orderForm.promoCardNumber.value);
    }
    if(valid)
    {
        specialPostcode(orderForm.postalCode.value);
    }
}
return valid;
} // end of verification

This is my HTML code for the form:

<form id="orderForm" method="post" action="x">
            <table id="formTable" cellpadding="5">
                <tr>
                    <td>
                        <h3>Shipping and Billing Information</h3>
                    </td>
                    <td>&nbsp;</td>
                </tr>
                <tr>
                    <td>First Name</td>
                    <td><input id="firstname" type="text" name="firstName" maxlength="30" /></td>
                </tr>
                <tr>
                    <td>Surname</td>
                    <td><input id="surname" type="text" name="surname" maxlength="30" /></td>
                </tr>
                <tr>
                    <td>Contact Telephone Number</td>
                    <td><input id=phoneNumber" type="text" name="phoneNumber" maxlength="30" /></td>
                </tr>
                <tr>
                    <td>Street Name</td>
                    <td><input id="streetName" type="text" name="streetName" maxlength="30" /></td>
                </tr>
                <tr>
                    <td>City</td>
                    <td><input id="city" type="text" name="city" maxlength="30" /></td>
                </tr>
                <tr>
                    <td>Postal Code</td>
                    <td><input id="postalCode" type="text" name="postalCode" maxlength="30" /></td>
                </tr>
                <tr>
                    <td>Email address</td>
                    <td><input id="emailAddress" type="text" name="emailAddress" maxlength="30" /></td>
                </tr>
                <tr>
                    <td>Contact Telephone Number</td>
                    <td><input id="billPhoneNumber" type="text" name="billPhoneNumber" maxlength="30" /></td>
                </tr>
                <tr>
                    <td>Promotional card</td>
                    <td><input id="promoCardNumber" type="text" name="promoCardNumber" maxlength="30" /></td>
                </tr>
                <tr>
                    <td>Credit Card Number</td>
                    <td><input id="billCardNumber" type="text" name="billCardNumber" maxlength="30" /></td>
                </tr>
                <tr>
                    <td>Credit Card Type</td>
                    <td>
                        <select id="billCardType" name="billCardType">
                            <option value="...">
                                Choose your card...
                            </option>
                            <option value="visa">
                                Visa
                            </option>
                            <option value="mastercard">
                                Mastercard
                            </option>
                        </select>
                    </td>
                </tr>
                <tr>
                    <td>Instructions</td>
                    <td><textarea id="instructions" name="instructions" rows="8" cols="30">Enter your requirements here or comments.</textarea></td>
                </tr>
                <tr>
                    <td colspan="2"><input id="submit" type="submit" name="Submit" value="Submit" onclick="return verification(document.getElementById('orderForm'));" /></td>
                </tr>
            </table>
        </form>

5 Answers5

3

Add a span near each field so you can use it for the validation message:

<td>First Name</td>
<td>
  <input id="firstname" type="text" name="firstName" maxlength="30" />
  <span id="firstname_error"/>
</td>

After that, just add the error message there, so instead of:

alert('You need to complete this field')

You would use:

document.getElementById('firstname_error').innerHTML = 'You need to complete this field'
Badaro
  • 3,460
  • 1
  • 19
  • 18
2

Simplest way is to put a hidden span tag below the input field like so

<input .... /> <br />
<span id="fieldname" style="display: none;">This field is required</span>

In Javascript you can do this

if(!valid)
{
  document.getElementById("fieldname").style = "block";
}
Virat Kadaru
  • 2,216
  • 4
  • 23
  • 28
0

I looked at the jQuery code. Looks like thousands of lines of code for some relatively simple validation. I would not recommend using the plugin for some simple validation - it is overkill.

Perception
  • 79,279
  • 19
  • 185
  • 195
0

I think you need to take a look at this http://www.w3schools.com/js/js_form_validation.asp for the validation thing then take the ideas you have here to display your message.

Minus
  • 729
  • 8
  • 20
0

Your way of validation form fields is absolutely terrible, a lot of unneded and bloated code which is not optimized at all.

I will strongly reccomend you use some sort of readyly available FormValidation script or have a look at this jQuery plugin
Using jQuery your code can look like this (plus you also get the messages to appear next to field):

$("#signupForm").validate({
    rules: {
        firstname: "required",
        lastname: "required",
        username: {
            required: true,
            minlength: 2
        },
        password: {
            required: true,
            minlength: 5
        },
        confirm_password: {
            required: true,
            minlength: 5,
            equalTo: "#password"
        },
        email: {
            required: true,
            email: true
        }
    }
})
duckyflip
  • 16,189
  • 5
  • 33
  • 36
  • Absolutely terrible? Geeze! Why don't you mail the poor guy some anthrax while you're at it? – Josh Stodola Jul 22 '09 at 14:39
  • Insulting someone is not a great way to get them to accept information you're telling them, even if the info is good. – Brian Ramsay Jul 22 '09 at 14:50
  • I tried using JQuery with the Validation Plugin which worked great but I couldn't work out how to add the promotional message on submit if the user met certain criteria on their postcode which is validated using a regex. I know I need to use submitHandler but wasn't sure how to write the code –  Jul 22 '09 at 16:03