Stop numerical values & allow numerical values JavaScript - javascript

I was adding some JavaScript validation to my page and found that I couldn't find any helpful sources to tell me on how to stop numerical values and allow them on different input boxes. I am very new to JavaScript and aren't quite up to grips with it yet. I know VB has a command similar to what I am asking for: isNumeric()
Here is the code what I want to stop numerical values in:
if (document.ExamEntry.name.value=="") {
alert("You must enter your name \n");
document.ExamEntry.name.focus();
document.getElementById('name').style.color="red";
result = false;
}
if (document.ExamEntry.subject.value=="") {
alert("You must enter the subject \n");
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color="red";
result = false;
}
Here is the code that I want to ONLY allow numerical values in:
if (document.ExamEntry.CadNumber.value.length!== 4) {
alert("Make sure you only have 4 numbers! \n");
document.ExamEntry.CadNumber.focus();
document.getElementById('CadNumber').style.color="red";
result = false;
}
---EDIT---
Here is what I have got so far now, it works sort of however it contstantly appears now... I was wondering if you knew anymore?
Stop Numerical values:
if (document.ExamEntry.subject.value) {
isNaN(parseInt(1));
alert("Please make sure you only have letters! \n");
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color="red";
result = false;
}
ONLY allow numerical values:
if (document.ExamEntry.CadNumber.value) {
isNaN(parseInt(""));
alert("Please make sure you only have numbers! \n");
document.ExamEntry.CadNumber.focus();
document.getElementById('CadNumber').style.color="red";
result = false;
}

Look up isNaN and parseInt - they should get you started. From the JS console,
isNaN(parseInt("foo"))
true
isNaN(parseInt(12))
false
isNaN is like the opposite of your VBA isNumeric so you need to use it with parseInt on the document.ExamEntry.CadNumber.value
Use it like this:
if (isNaN(parseInt(document.ExamEntry.CadNumber.value))) {
alert("Please make sure you only have numbers! \n");
document.ExamEntry.CadNumber.focus();
document.getElementById('CadNumber').style.color="red";
result = false;
}

To give a small example of how it could work, you could check this small snippet.
In a sense, at the moment you submit your form, it will go to the validate function, that will then check your form for the requirements.
The numbers only / text only is implied by the type (and your browser can also help), and the error message is supplied in a title.
When one field fails, the validation stops and throws the error.
Note, if you have any other elements you want to check (like selects) you would have to do some extra work still ;)
And if you want to learn more about the element types you could set, you could check it here as well
function validate(form) {
var succeeded = true,
i, len, item, itemArray, firstErrorField;
if (!form) {
succeeded = false;
} else {
itemArray = form.getElementsByTagName('input');
for (i = 0, len = itemArray.length; i < len && succeeded; i++) {
item = itemArray[i];
switch (item.type) {
case 'text':
if ((!item.value && item.required) || !isNaN(parseInt(item.value))) {
succeeded = false;
}
break;
case 'number':
if ((!item.value && item.required) || isNaN(parseInt(item.value))) {
succeeded = false;
}
break;
}
if (!succeeded) {
firstErrorField = item.title || item.id || item.name;
}
}
}
if (!succeeded) {
alert('please check your input!\r\n' + firstErrorField);
}
return succeeded;
}
<form onsubmit="return validate(this);">
<fieldset>
<table>
<tr>
<td>Name:</td>
<td>
<input type="text" id="name" title="name is required" required />
</td>
</tr>
<tr>
<td>Age:</td>
<td>
<input type="number" id="age" required="required" min="0" title="age is required" />
</td>
</tr>
<tr>
<td colspan="2">
<button type="submit">Submit</button>
</td>
</tr>
</table>
</fieldset>
</form>

Related

Form validation woes

New to JS guy here! I feel I have understanding of what my code is doing, but it still won't work.
The bug is (supposedly) with the validation for the phone number form, I have code that -as far as I know- should work (but does not).
Note that I have not got code to validate Address, post code and CC. The Idea is that I can apply your solutions to theses, seeing as they are similar to Phone number.
Also note I did try isNaN, but it was being "weird". Hope thats not too vague, but I'm sure some of you will "know" what I'm talking about.
Here we go (Sorry if my function is a bit long, let me know if its bad practice or whatever.)
Lets stay away from blunt answers if we can? I'd like to know whats wrong so I can fix it myself, walk me through it if you have the mind to be patient :)
JS and HTML:
function detailCheck() {
var phNoLength = document.getElementById('phNo').value.length; //get value for phone number from form for checking
var cardNoLength = document.getElementById('cardNo').value.length; //get value for card number length for checking
var postCodeLength = document.getElementById("postCode").value.length //get value for post code length
var a = /^[A-Za-z]+$/;
var b = /^[-+]?[0-9]+$/;
for (var i = 0; i < 5; i++) {
details = document.getElementById("myForm")[i].value;
if (details === "") {
var i = ("Please enter ALL your details.");
document.getElementById("formTital").innerHTML=i;
return;
} else {
if(phNoLength != 7) {
var i = "Please use a phone number with a length of 7";
document.getElementById("formTital").innerHTML = i;
} else {
if(b.test(document.getElementById("phNo").value)) {
if(postCodeLength === 4){
var f_nameLength = document.getElementById('fName').value.length;
var l_nameLength = document.getElementById('lName').value.length;
if(f_nameLength < 3) {
var i = "First name not long enough"
document.getElementById("formTital").innerHTML=i;
} else {
if(a.test(document.getElementById("fName").value)) {
if(l_nameLength < 3) {
var i = "Last name not long enough"
document.getElementById("formTital").innerHTML=i;
} else {
if(a.test(document.getElementById("lName").value)) {
if(cardNoLength === 4) {
if(isNaN(cardNoLength)) {
var i = "Your card number must be numbers only";
document.getElementById("formTital").innerHTML=i;
} else {
//---- End result ----//
toggleContent();
//--------------------//
}
} else {
var i = "Your card number must have four numbers";
document.getElementById("formTital").innerHTML = i;
}
} else {
var i = "Please only use letters in your last name";
document.getElementById("formTital").innerHTML=i;
}
}
} else {
var i = "Please only use letters in your first name";
document.getElementById("formTital").innerHTML=i;
}
}
} else {
var i = "Please use a post code with a length of four";
document.getElementById("formTital").innerHTML = i;
}
} else {
var i = "only use numbers in your Phone number";
document.getElementById("formTital").innerHTML=i;
}
}
}
}
}
<form id="myForm" action="form_action.asp">
First name: <br> <input class="formInput" type="text" id="fName" name="fName"><br>
Last name: <br> <input class="formInput" type="text" id="lName" name="lName"><br>
Phone Number: <br> <input class="formInput" type="number" id="phNo" name="phNo" maxlength="7"><br>
Credit Card Number: <br> <input class="formInput" type="password" id="cardNo" name="cardNo" maxlength="4"><br>
Address: <br> <input class="formInput" type="text" id="address" name="address"><br>
Post code: <br> <input class="formInput" type="number" id="postCode" name="postCode" maxlength="4"><br>
</form>
It is not obvious when you want the validation to occur (you included a function but it is not clear whether you want it to be an event handler or not).
Your regex seems to be fine. I am including a stripped-down JSFiddle with a single input to which I attached an event handler for keyup and showed the result of .test() for your regex.
See it here.
In regards to your code, it is fairly messy. In terms of form validation. I assume you meant to display a single status message for the user, so you would want to you want to first figure out the priority of your validation. One cleaner option would be to use a function with ordered returns, for example take this pseudo-code:
function getErrorMessage(){
// if name is invalid
// return 'Your name is invalid.';
// if phone is invalid
// return 'Your phone is invalid.';
// ...
// return '';
}
Nesting so many conditional statements can lead to very messy, very non-maintainable spaghetti code. If you are new to Javascript, it is best to learn the best practices early on, as it will save you a lot of headache and facepalms in the future.
If I did not understand your question correctly, please let me know.

How to validate login trough post request upon clicking the login button in javascript?

I'm having problems getting this code to validate when clicking on the login button.
** my html code **
<form action="abc.php"
method="post"
onsubmit="return jcheck();">
<div id="id_box">
<input type="text"
name="email"
id="id_text" placeholder="E-mail" >
<div id="pass_box">
<input type="password"
name="password" id="pass_text" placeholder="Password">
<div id="submit_box">
<input
type="submit"
id="sub_box"
onClick="click_event()"
value="Login">
my javascript code:
function click_event(){
jcheck();
function validate_ID(){
var email = document.getElementById('id_text');
var filter = /^[a-z0-9](\.?[a-z0-9]){1,}#threadsol\.com$/;
var filter1 = /^[a-z0-9](\.?[a-z0-9]){1,}#intellocut\.com$/;
var flag=0;
if (filter.test(email.value)==false
&& filter1.test(email.value)==false ) {
$('#warn_pass').html("Enter Valid Email or Password");
$("#e_asterics").html("");
return false;
} else
return true;
}
function validate_Pass() {
var pass =document.getElementById('pass_text');
var filter = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s). 4,}$/;
if (filter.test(pass.value)==false ) {
$('#warn_pass').html("Enter Valid Email or Password");
$("#p_asterics").html("");
return false;
} else
return true;
}
function jcheck();
$("#e_asterics").html("");$("#p_asterics").html("");
$('#warn_text').html("");$('#warn_pass').html("");
var name = jQuery.trim($("#id_text").val());var pas = jQuery.trim($("#pass_text").val());
if ((name.length == 0) && (pas.length == 0)) {
$('#warn_text').html("*Indicates required field");
$('#warn_pass').html("* Indicates required field");
$("#e_asterics").html("*");$("#p_asterics").html("*"); }
else if (name.length == 0)) {
$("#e_asterics").html("*");
$("#p_asterics").html("");
$('#warn_pass').html("Email Id Required");
} else if ((pas.length == 0)) {
if(name.length != 0)
{
validate_ID();
} else {
$("#e_asterics").html("*");
$('#warn_text').html("Enter Email Id");
}
$("#p_asterics").html("*");
$('#warn_pass').html("Password Required");
}
}
return false;
}
For starters you should always indent your code so errors are easier to find. I helped you do a bit of indenting and there are a lot of problems in the code. One thing you are doing wrong is you need to close functions, else branches and html tags.
All HTML tags should end with an end tag or be closed immediately.
Example <div></div> or <div /> if you don't do this the browser may render your page differently on different browsers. You have missed this on your input tags you divs and your form tag. Perhaps you should check the whole html document for more of these errors.
Functions should in javascript should always look like this
function name(parameters, ...) {
}
or like this
var name = function(parameters, ...) {
}
the the name and parameters may vary but generally the function should look like this.
if statements else branches and else if branches should all have enclosing brackets for their code.
if () {
//code
} else if () {
//code
} else {
//code
}
If you do not close start and close else brackets the javascript will behave in very strange and unexpected ways. In fact i think your code might not even compile.
If you are using chrome please press Ctrl + Shift + J and look in the Console tab. You should see some error messages there. When you click the submit button.
Also using onClick on the submit button may be dangerous as I don't think this blocks submit. A better way to achieve the requested functionality is probably to either use a button type input and go with onClick or use the onSubmit function on the form. You are currently using both and its really no way to tell if click_event or jcheck will run first. Perhaps you should debug and see in which order the function calls happen. You can use chrome to debug by pressing CTRL + Shift + J and setting debug points in the Source tab.
You have a minor stylistic error as well where you compare the result of the regexp test() with false. The return value of test is already a Boolean and does not need to be compared.
Here is a guestimation of how the HTML should look. Its hard to say if its right as I have no more info to go on than your code and it has a lot of problems.
<form action="abc.php" method="post" onsubmit="return jcheck();">
<div id="id_box">
<input type="text" name="email" id="id_text" placeholder="E-mail" />
</div>
<div id="pass_box">
<input type="password" name="password" id="pass_text" placeholder="Password">
</div>
<div id="submit_box">
<input
type="submit"
id="sub_box"
value="Login" />
</div>
</form>
Here is what the js might look like. Here the missing brackets makes it difficult to tell where functions should end so I have had to guess a lot.
/* I find it hard to belive you wanted to encapsule your functions inside the
click_event function so I took the liberty of placing all
functions in the glonbal scope as this is probably what you inteneded.
I removed the click_event handler as it only does the same thing as the onSubmit.
*/
function validate_ID() {
var email = document.getElementById('id_text');
var filter = /^[a-z0-9](\.?[a-z0-9]){1,}#threadsol\.com$/;
var filter1 = /^[a-z0-9](\.?[a-z0-9]){1,}#intellocut\.com$/;
var flag=0;
// Or feels better here as there is no way the email ends with bot #intellocut and #threadsol
// It also feels strange that these are the invalid adresses maby you messed up here and should change
// the contents of the else and the if branch.
if (filter.test(email.value) || filter1.test(email.value)) {
$('#warn_pass').html("Enter Valid Email or Password");
$("#e_asterics").html("");
return false;
} else {
return true;
}
}
// This funcion is not used Im guessing you should have used it in
function validate_Pass() {
var pass =document.getElementById('pass_text');
/* The filter below could cause problems for users in deciding password unless
you tell them some where what the rules are.
It was missing a { bracket before the 4 at the end that I added make sure
it is right now. If you are going to use the code.
*/
var filter = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s). {4,}$/;
if (filter.test(pass.value)) {
$('#warn_pass').html("Enter Valid Email or Password");
$("#p_asterics").html("");
return false;
} else {
return true;
}
}
/* There are betterways to deal with multiple validation than chaining them like
this but Im guessing this will work. Im guessing that if you want to use the
password validation you should call it some where in this function.
like so 'validate_Pass()'
*/
function jcheck() {
$("#e_asterics").html("");$("#p_asterics").html("");
$('#warn_text').html("");$('#warn_pass').html("");
var name = jQuery.trim($("#id_text").val());var pas = jQuery.trim($("#pass_text").val());
if ((name.length === 0) && (pas.length === 0)) {
$('#warn_text').html("*Indicates required field");
$('#warn_pass').html("* Indicates required field");
$("#e_asterics").html("*");
$("#p_asterics").html("*"); }
else if (name.length === 0) {
$("#e_asterics").html("*");
$("#p_asterics").html("");
$('#warn_pass').html("Email Id Required");
} else if (pas.length === 0) {
if(name.length !== 0) {
validate_ID();
} else {
$("#e_asterics").html("*");
$('#warn_text').html("Enter Email Id");
}
}
}

JavaScript Comparison Operators Not Working

i need compare two values using Less Than or Greater Than, but it's not working fine. Here below my code.
//JAVASCRIPT
<script type="text/javascript">
function validform()
{
var balanvar = document.myform.balance.value,
currntvar = document.myform.currnt.value;
if( currntvar == "" ) { document.myform.currnt.focus(); document.getElementById("curntid").style.borderColor = "red"; return false; } // Must be filled error
if(currntvar > balanvar) { document.myform.currnt.focus(); document.getElementById("curntid").style.borderColor = "red"; return false; } else { document.getElementById("curntid").style.borderColor = "green"; } // Maximum value error
}
</script>
//HTML
<form name="myform" method="post" action="">
<input type="text" name="balance" id="balanceid" value="12000"/>
<input type="text" name="currnt" id="curntid"/>
<input type="submit" name="submit" value="Proceed" onclick="return validform();"/>
</form>
What i want is, i have to enter less than "balance" value in "currnt" text box, if i entered maximum value compare to "balance" text box mean, have to throw error message.
Problem Is, when clicking proceed without filling "currnt" it's showing error. and when entering value 15000 in "currnt" means its showing error. But when entering value 100000 in "currnt" means its not giving error. i don't know what error is this. please help me.
The .value property returns a string. hence you comparisons are done using string comparisons, which most of the time do yield other results than number comparisons.
To solve that, convert to numbers first using parseFloat() or parseInt():
function validform()
{
var balanvar = parseFloat( document.myform.balance.value ),
currntvar = parseFloat( document.myform.currnt.value );
if( isNaN( currntvar ) ) { document.myform.currnt.focus(); document.getElementById("curntid").style.borderColor = "red"; return false; } // Must be filled error
if(currntvar > balanvar) { document.myform.currnt.focus(); document.getElementById("curntid").style.borderColor = "red"; return false; } else { document.getElementById("curntid").style.borderColor = "green"; } // Maximum value error
}

How to call two functions on a form submit

I am trying to do javascript form validation, and to do this I need to call two functions. One for the password and on for the username (I will also need to call more later on).
Here is my JS code:
function validateUserName(NewUser)
{
var u = document.forms["NewUser"]["user"].value
var uLength = u.length;
var illegalChars = /\W/; // allow letters, numbers, and underscores
if (u == null || u == "")
{
alert("You left Username field empty");
return false;
}
else if (uLength <4 || uLength > 11)
{
alert("The Username must be between 4 and 11 characters");
return fasle;
}
else if (illegalChars.test(u))
{
alert("The username contains illegal characters");
return false;
}
else
{
return true;
}
}
function validatePassword(pwd, confirmPwd)
{
var p = document.forms["NewUser"]["pwd"].value
var cP = document.forms["NewUser"]["cP"].value
var pLength = p.length;
if (p == null || p == "")
{
alert("You left the password field empty");
return false;
}
else if (pLength < 6 || pLength > 20)
{
alert("Your password must be between 6 and 20 characters in length");
return false;
}
else if (p != cP)
{
alert("Th passwords do not match!");
return false;
}
}
and here is my HTML form:
<form name = "NewUser" onsubmit= "return validateUserName(), return validatePassword()" action = "">
<tr>
<td>Username:</td>
<td><input type = "text" name = "user"/></td>
</tr>
<tr>
<td class = "Information"><em>Must be 4-11 characters.<br/>Only numbers, letters and underscores.</em></td>
</tr>
<tr>
<td>Password:</td>
<td><input type = "password" name = "pwd"/></td>
<tr>
<td class = "Information"><em>6-20 characters</em></td>
</tr>
<tr>
<td>Confirm Password:</td>
<td><input type = "password" name = "confirmPwd"/></td>
<tr>
<td class = "Information"><em>just in case you didn't make mistakes!</em></td>
</tr>
<input type = "submit" value = "Submit"/>
Please ignore the table code.
Should I rather just put it all in one function? Or is there a way to call two functions at once?
You have multiple ways of approaching this, the easiest for your current set up would be:
combined function
The following will run both functions no matter what state is returned each time, because they are not executed inline as part of a logical expression which will "short circuit" when getting a false value:
function validateForm(){
var validation = true;
validation &= validateUserName();
validation &= validatePassword();
return validation;
}
And then in your form markup:
<form onsubmit="return validateForm()">
If would probably be advisable, in the interests of making more reusable code, to modify your validation functions so that they accept a form argument. This would mean you could do the following:
<form onsubmit="return validateForm(this);">
.. and have your receiving function do the following:
function validateForm(form){
var validation = true;
validation &= validateUserName(form);
validation &= validatePassword(form);
return validation;
}
add multiple events
You could also implement this via the preferred way of applying event listeners which is to use addEventListener instead of the html attribute onsubmit:
/// wait for window load readiness
window.addEventListener('load', function(){
/// you could improve the way you target your form, this is just a quick eg.
var form;
form = document.getElementsByTagName('form')[0];
form.addEventListener('submit', validateUserName);
form.addEventListener('submit', validatePassword);
});
The above assumes that it's required to support modern browsers. If you wish to support older versions of internet explorer you'd be better off making a function to apply your event handling e.g:
function addEventListener( elm, evname, callback ){
if ( elm.addEventListener ) {
elm.addEventListener(evname, callback);
}
else if ( elm.attachEvent ) {
elm.attachEvent('on'+evname, callback);
}
}
This second option makes it harder to exert a global control over what gets validated, where, when and in what order, so I'd recommend the first option. However I'd would also recommend at least applying your singular submit handler using the JavaScript method above, rather than using onsubmit="".
Simply combine the two with the logical AND operator:
<form name="NewUser" onsubmit="return validateUserName() && validatePassword();" action="">
<tr>
<td>Username:</td>
<td><input type="text" name="user"/></td>
</tr>
<tr>
<td class="Information"><em>Must be 4-11 characters.<br/>Only numbers, letters and underscores.</em></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="pwd"/></td>
<tr>
<td class="Information"><em>6-20 characters</em></td>
</tr>
<tr>
<td>Confirm Password:</td>
<td><input type="password" name="confirmPwd"/></td>
</tr>
<tr>
<td class="Information"><em>just in case you didn't make mistakes!</em></td>
</tr>
<input type="submit" value="Submit"/>
</form>
There are a few approaches to this. One is to create a function, such as submitForm() which then calls your two other functions. Perhaps using those function calls as part of if statements to provide client side validation.
The other method is to override the default submit functionality of the form, and instead call the functions as you see fit. jQuery provides an easy approach for this. Have a look at http://api.jquery.com/submit/ for more information.
Ideally, the validateUser() and validatePassword() functions would be merged into the one function validateUser(). You may want to provide the code of your current functions for advice on how to do that, if you're stuck...
Hope this helps :)
Why you are creating two different functions to validate both username and passwords, by the way you can go with this too like below:
Create Another third Function in which these two have to call and check if both returns true then return true otherwise its shows message or whatever you want to do.
Here is the code by which you can do it:
function validateUserName(NewUser) {
var u = document.forms["NewUser"]["user"].value
var uLength = u.length;
var illegalChars = /\W/; // allow letters, numbers, and underscores
if (u == null || u == "") {
alert("You left Username field empty");
return false;
}
else if (uLength < 4 || uLength > 11) {
alert("The Username must be between 4 and 11 characters");
return fasle;
}
else if (illegalChars.test(u)) {
alert("The username contains illegal characters");
return false;
}
else {
return true;
}
}
function validatePassword(pwd, confirmPwd) {
var p = document.forms["NewUser"]["pwd"].value
var cP = document.forms["NewUser"]["cP"].value
var pLength = p.length;
if (p == null || p == "") {
alert("You left the password field empty");
return false;
}
else if (pLength < 6 || pLength > 20) {
alert("Your password must be between 6 and 20 characters in length");
return false;
}
else if (p != cP) {
alert("Th passwords do not match!");
return false;
}
}
function finalvalidate() {
var newuser = $('[id$=newuser]').val();
var usernameresult = validateUserName(newuser);
var pwd = $('[id$=pwd]').val();
var confirmPwd = $('[id$=confirmPwd]').val();
var pwdresult = validatePassword(pwd, confirmPwd);
if (usernameresult == true && pwdresult == true) {
return true;
} else {
return false;
}
}
Hope this will work for you..
Create one function to call all your validators:
function validate() {
return validateUserName() && validatePassword();
}
HTML
<form name="NewUser" onsubmit="return validate()" action="">
Also in your password validation function you refer to incorrect field name.
Fixed code: http://jsfiddle.net/6sB29/
If you want to alert all the errors (not only the first) you can try something like this:
function validate() {
var name = validateUserName(),
pass = validatePassword();
return name && pass;
}
http://jsfiddle.net/6sB29/1/
try this
onsubmit="return fun2() && fun3();"

How to check for empty values on two fields then prompt user of error using javascript

I hope I can explain this right I have two input fields that require a price to be entered into them in order for donation to go through and submit.
The problem that I am having is that I would like the validation process check to see if one of the two fields has a value if so then proceed to submit. If both fields are empty then alert.
This is what I have in place now after adding some of the input i received earlier today:
function validate_required(field,alerttxt)
{
with (field)
{
if (value==null||value=="")
{
alert(alerttxt); return false;
}
else
{
return true;
}
}
}
function validate_form(thisform)
{
with (thisform)
{
if (validate_required(billing_name_first,"You must enter your first name to donate")==false)
{billing_name_first.focus();return false;}
else if (validate_required(billing_name_last,"You must enter your last name to donate")==false)
{billing_name_last.focus();return false;}
else if (validate_required(billing_address_street1,"You must enter your billing street address to donate")==false)
{billing_address_street1.focus();return false;}
else if (validate_required(billing_address_city,"You must enter your billing address city to donate")==false)
{billing_address_city.focus();return false;}
else if (validate_required(billing_address_state,"You must enter your billing address state to donate")==false)
{billing_address_state.focus();return false;}
else if (validate_required(billing_address_zip,"You must enter your billing address zip code to donate")==false)
{billing_address_zip.focus();return false;}
else if (validate_required(billing_address_country,"You must enter your billing address country to donate")==false)
{billing_address_country.focus();return false;}
else if (validate_required(donor_email,"You must enter your email address to donate")==false)
{donor_email.focus();return false;}
else if (validate_required(card_number,"You must enter your credit card number to donate")==false)
{card_number.focus();return false;}
else if (validate_required(card_cvv,"You must enter your credit card security code to donate")==false)
{card_cvv.focus();return false;}
else if (validate_required(input1,"Need to enter a donation amount to continue")==false && validate_required(input2, "Need to enter a donation amount to continue")==false)
{
input1.focus();
return false;
}
}
}
This works fine... other than the fact that I get a message that reads error undefined... which i click ok about 2 times then I get the correct alert and instead of allowing me to correct the problem in IE7 and IE8 the form just processes.
Thanks guys any help would do
Matt
If I am understanding correctly, you only want to do the alert if both of the inputs are empty. If that's the case here's a refactoring of your code that will handle that.
function validate_required(field)
{
with (field)
{
if (value==null||value=="")
{
return false;
}
else
{
return true;
}
}
}
function validate_form(thisform)
{
with (thisform)
{
if (validate_required(input1)==false && validate_required(input2)==false)
{
alert('Need a donation to continue');
input1.focus();
return false;
}
}
}
take the alert() out of your assessment function- you're trying to do too much at once. a function to determine if input is valid or not should do only that one thing.
determine the state of your inputs first and then do something like
var field1Pass = validate_required(input1);
var field2Pass = validate_required(input2);
if ( !(field1Pass && field2Pass) ) {
alert("Need a donation amount to continue");
// TODO: logic to determine which field to focus on
return false;
}
var msg = "Need a donation amount to continue";
function validate_required(value) {
if(isNaN(value) || value == null || value == "") {
return false;
}
return true;
}
function validate_form(thisform) {
var i1 = validate_required($(thisform.input1).val());
var i2 = validate_required($(thisform.input2).val());
if(!(i1 && i2)) {
alert(msg);
thisform.input2.focus();
return false;
}
}
Look at the jQuery validation plugin. With the plugin it would just be a matter setting up the rules properly. You could get fancier and replace the default messages if you want. Check out the examples.
<script type="text/javascript">
$(function() {
$('form').validate({
'input1': {
required: {
depends: function() { $('#input2').val() == '' }
}
}
});
});
</script>
This sets it up so that input1 is required if input2 is empty, which should be sufficient since if input1 has a value, you don't need input2 and if neither has a value, then it will show your message for input1.
<input type="text" name="input1" />
<input type="text" name="input2" />
Here's my take, with refocusing on the first field that failed:
<body>
<form action="#" onsubmit="return validate(this);">
<input type="text" name="val0" /><br />
<input type="text" name="val1" /><br />
<input type="submit" />
</form>
<script type="text/javascript">
function validate(form) {
var val0Elem = form.val0, val1Elem=form.val1, elementToFocus;
// check fields and save where it went wrong
if (!numeric(val0Elem.value)) {elementToFocus=val0Elem;}
else if (!numeric(val1Elem.value)) {elementToFocus=val1Elem;}
// if there is an element to focus now, some validation failed
if (elementToFocus) {
alert('Enter numbers in both fields, please.')
// using select() instead of focus to help user
// get rid of his crap entry :)
elementToFocus.select();
// ..and fail!
return false;
}
// Helper function, "if a string is numeric":
// 1: it is not 'falsy' (null, undefined or empty)
// 2: it is longer than 0 too (so that '0' can be accepted)
// 3: it passes check for numericality using the builtin function isNaN
function numeric(s) {return (s && s.length>0 && !isNaN(s));}
}
</script>
</body>

Categories