/    Sign up×
Community /Pin to ProfileBookmark

Form Javascript Validation

Hello, I’m hoping someone is able to point me in the right direction. Basically I’ve got a form in which I’m using a Javascript validation script from [url]http://www.webcheatsheet.com/javascript/form_validation.php[/url]

Although I’ve been successful in validating most of the fields in my form, I’m having problems ensuring some fields only allow numerical values, i.e. £ amounts. I’m using the script below and although it works, it requires the field to be completed and ideally I’m looking for either the field to be empty or to only allow numbers.

Thanks in advance
Richard

</script>

<script type=”text/javascript”>
function validateFormOnSubmit(theForm) {
var reason = “”;

reason += validateAmt(theForm.TimeAtAddress_1stApp);

if (reason != “”) {
alert(“Some fields need attention:n” + reason);
return false;
}

return true;
}

function validateAmt(fld) {
var error = “”;
var stripped = fld.value.replace(/[(). ]/g, ”);

if (isNaN(parseInt(stripped))) {
error = “A number field contains illegal characters. Please see the highlighted field/s.n”;
fld.style.background = ‘Yellow’;
} else {
fld.style.background = ‘White’;
}

return error;

}

</script>

to post a comment
JavaScript

3 Comments(s)

Copy linkTweet thisAlerts:
@WolfShadeMar 15.2011 — I, personally, have never been a fan of that format of form validation. Mostly because it produces an alert box that tells the user about one thing at a time that is incorrect with the form. If there's only one issue, no problem; but if there are ten issues, you get ten different alert boxes, once each for every time the form is submit.

Annoying.

Get everything that is incorrect with the form, all at once, and deliver all issues in one alert. If you're clever, you can even use an array to keep track of which form elements need attention, and then set focus on the element in position 0 after the alert box is closed.

For your example, let's say your form is named "orderForm" and there is only one field, "price". You want to make sure that the field is either empty OR contains only a numeric value. Assign an "onSubmit" event handler to the form to call a function, passing the ID of the form to it.
[code=html]
<form name="orderForm" id="orderForm" onSubmit="return checkData(this.id);">
<input type="text" name="price" id="price">
<input type="submit" name="submitBtn" id="submitBtn">
</form>
[/code]

Now for validation:
<i>
</i>[color=red]&lt;script type="text/javascript"&gt;[/color]
[B]function[/B] checkData(tid) {
tid = tid || 0;// If tid is passed, tid = tid; if not, tid = 0 (ideally form index)
var warn = "";
var df = document.forms[tid]; // Assign the form name to a variable, shortens code
var thisValue = df.price.value;
var thisMask = /^d{1,5}.d{2}$/; //0.00 - 99999.99 is valid
if(thisValue.length &gt; 0) { //If it isn't blank..
if(!thisValue.match(thisMask)) {
warn += "Invalid price";
}
}
if(warn != "") { alert(warn); return false; } else { return true; }
}
[color=red]&lt;/script&gt;[/color]

If the form has more than the one element, you can keep following the same example and just check (at the end) for the value of warn - if it's empty, all is good; if not, stop submit and alert.

^_^
Copy linkTweet thisAlerts:
@CMLSauthorMar 16.2011 — Thanks WolfShade

Unfortuntely I've already implimented the existing validation functions and am just looking to increase it's funtion at the moment but I will definately keep your reply handy for my next form.

I'm actually nearly there on most bits but am stuck on one last field. I've a field called 'SecurityCode' at the bottom of the form to try and stop spammers, etc and although I can stop it from being left empty I don't know how to get users to enter only certain text, i.e. "ABCDE". Do you know how I can do this? Below is a shortened version my code, showing just the function checking the SecurityCode...



</script>

<script type="text/javascript">

function validateFormOnSubmit(theForm) {

var reason = "";

reason += validateCode(theForm.SecurityCode);


function validateCode(fld) {

var error = "";

var valcode = /[0-1]/;

if (fld.value == "") {
fld.style.background = 'Yellow';
error = "You didn't enter the validation code. Please see the highlighted field.n"
} else if (fld.value.match(valcode)) {
fld.style.background = 'Yellow';
error = "You didn't enter the correct validation code. Please see the highlighted field.n";
} else {
fld.style.background = 'White';
}
return error;

}

</script>
Copy linkTweet thisAlerts:
@CMLSauthorMar 17.2011 — A new day and the fix came straight to me! Simple when I think about it.

Below is my working code. Thanks for your help.


function validateCode(fld) {

var error = "";

if (fld.value == "") {
fld.style.background = 'Yellow';
error = "You didn't enter the validation code. Please see the highlighted field.n"
} else if (fld.value == "1234") {
fld.style.background = 'White';
} else {
fld.style.background = 'Yellow';
error = "You didn't enter the correct validation code. Please see the highlighted field.n";
}
return error;

}
×

Success!

Help @CMLS spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...