最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Form Validation using JavaScript - Stack Overflow

programmeradmin3浏览0评论

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 petition 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 ments.</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>

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 petition 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 ments.</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>
Share Improve this question asked Jul 22, 2009 at 14:28 PocketPocket 1
  • At least try. What's wrong with the alerts? – Josh Stodola Commented Jul 22, 2009 at 14:34
Add a ment  | 

5 Answers 5

Reset to default 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 plete this field')

You would use:

document.getElementById('firstname_error').innerHTML = 'You need to plete this field'

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";
}

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 recend 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
        }
    }
})

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

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

发布评论

评论列表(0)

  1. 暂无评论