I have a javascript project I am working on that take information and submits it. I am supposed to validate that the quantity inputs only have numbers in them and pop up an alert box and not submit if they do not. They can be blank as long as if they have anything input it is only numbers. I have validated it, and looked at the submission page and it shows that if I put in letters the particular quantity field does not submit (I have three quantities), but everything else does. It is supposed to throw up an alert and stop the page from submitting if any of the quantities are not numbers. I have looked at this over and over and tried a few things, but cannot seem to find my error. I would appreciate any direction on where to look to correct this.
<script>
//function to check for valid fruit quantities
function certifyDigits() {
var b = document.getElementById("blueberries").value;
var c = document.getElementById("cherries").value;
var s = document.getElementbyId("strawberries").value;
if (!b.match(/^\d+$/)) {
alert("Please enter only numbers for quantity!");
return false;
}
if (!c.match(/^\d+$/)) {
alert("Please enter only numbers for quantity!");
return false;
}
if (!s.match(/^\d+$/)) {
alert("Please enter only numbers for quantity!");
return false;
}
}
</script>
</head>
<body>
<h2>Fruit Purchasing Form</h2>
<table class="main">
<tr>
<th class="a"> </th>
<th class="a">Blueberries</th>
<th class="a">Cherries</th>
<th class="a">Strawberries</th>
</tr>
<tr>
<th class="a">Price</th>
<td class="b">$2.50</td>
<td class="b">$4.40</td>
<td class="b">$8.00</td>
</tr>
<tr>
<th class="a">Shipping Weight</th>
<td class="b">2.0</td>
<td class="b">4.0</td>
<td class="b">4.0</td>
</tr>
</table>
<br />
<br />
<br />
<br />
<form name="fruitOrder" action="http://www.textXXX.php" method="post" onSubmit="return certifyDigits()">
<h3>Select Quantity of Fruit Desired</h3>
<br />
<p>Blueberries:</p>
<input id="blueberries" type="text" size=5>
<p>Cherries:</p>
<input id="cherries" type="text" size=5>
<p>Strawberries:</p>
<input id="strawberries" type="text" size=5>
<br />
<br />
<h3>Customer Information</h3>
<br />
<label>Your Last Name:
<input type="text" name="lastname" id="lastname" size="25" />
</label>
<br />
<label>Your First Name:
<input type="text" name="firstname" id="firstname" size="25" />
</label>
<br />
<label>Street Address:
<input type="text" name="street" id="street" size="60" />
</label>
<br />
<label>City, State, Zip Code:
<input type="text" name="citystatezip" id="citystatezip" size="60" />
</label>
<br />
<h3>Payment Method</h3>
<label>Visa
<input type="radio" name="payment_type" id="payment_type_Visa" value="Visa" checked />
</label>
<br />
<label>Mastercard
<input type="radio" name="payment_type" id="payment_type_MC" value="MC" />
</label>
<br />
<label>American_Express
<input type="radio" name="payment_type" id="payment_type_amex" value="amex" />
</label>
<br />
<br />
<input type="submit" value="SUBMIT" />
</form>
The javascript match() function always returns an array. If the match is true, then the array will contain the matching value. If the match is false, then the array will contain an empty string. Change your if statements to
if (b.match(/^\d+$/)[0] === "") {
That should fix it.
Why not validate the input for numbers only?
function validate_numbers(evt){
var theEvent=evt || window.event;
var key=theEvent.keyCode || theEvent.which;
key=String.fromCharCode(key);
var regex=/[0-9]|\.|\,|\/|\ /;
if(!regex.test(key)){
theEvent.returnValue=false;
if(theEvent.preventDefault)theEvent.preventDefault();
};
};
It should be: document.getElementById("strawberries").value;
Not: document.getElementbyId("strawberries").value;
You are using small letter b for getElementById which causes an error.
To easily see errors like this, enable preserve log on chrome. On my end the error is: Uncaught TypeError: document.getElementbyId is not a function
To prevent the page from sending on error add return false; in function certifyDigits(). You can also set variables that will store number of errors, if there is an error, return false.
See below.
function certifyDigits(){
var fruits = ["blueberries", "cherries", "strawberries"];
var errors_count = 0;
for(var ctr = 0; ctr < fruits.length; ctr ++){
if(! document.getElementById(fruits[ctr]).value.match(/^\d+$/)){
errors_count++;
}
}
if(errors_count > 0){
alert("Please enter only numbers for quantity!");
return false;
}
}
By the context, you were using match instead of test.
To make everything works correctly, use /^\d+$/.test(b) this will return True or False, and you may want to alert once if either of them input is incorrect (instead of three alerts), to do this include || in the if statement which stands for or, Cheers !
Related
How do I check multiple variable inputs at once to ensure that the regex is working? Everytime I enter anything, the form submits and doesn't alert anything.
I have tried test()method of regex validation too, and still no luck.
I am trying to validate user input with the following regex that makes to where anything that is not a number or blank space is considered a wrong input.
var format=/^(\s*|\d+)$/;
It only accepts numbers and blank spaces in the text box.
The following javascript is what I have:
var pitch = document.getElementById("pitch");
var chisel = document.getElementById("chis");
var saw = document.getElementById("saw");
//var arguments = [chisel, saw, pitch];
var format = /^(\s*|\d+)$/;
function regexTest() {
if (!chisel.match(format) && !saw.match(format) && !pitch.match(format)) {
alert("Repressed Action");
return false;
} else {
alert('Thank you');
}
}
<div class="lab">
<form method="post" action="http://weblab.kennesaw.edu/formtest.php">
Chisels: <input type="text" name="chisels" id="chis" size="5" /> Saw: <input type="text" name="saw" id="saw" size="5" /> Pitchfork: <input type="text" name="pitchfork" id="pitch" size="5" />
<br /> Customer Name: <input type="text" name="customer name" size="25" />
<br /> Shipping Address: <input type="text" name="shipping address" size="25" />
<br /> State:
<input type="radio" id="master" name="card" value="master" /><label for="master">MasterCard</label>
<input type="radio" id="american" name="card" value="american" /><label for="american">American Express</label>
<input type="radio" id="visa" name="card" value="visa" /><label for="visa">Visa</label>
<br />
<input type="reset" value="Reset" />
<div class="lab">
<button onclick="regexTest()">Submit</button>
<button onclick="return false">Cancel</button>
</div>
There are a number of issues with your code, below I've refactored it to be a bit easier to read and so it works.
The validation listener should be on the form's submit handler, not the submit button since forms can be submitted without clicking the button. Also, if you pass a reference to the form to the listener, it's much easier to access the form controls by name.
You should get the values of the form controls when the submit occurs, not before. Your code gets the values immediately, before the user has done anything (and possibly before the form even exists), so put that code inside the listener function.
Lastly, the regular expression needs to match anything that isn't a space or digit, so:
/[^\s\d]/
seems appropriate. However, this will still allow the form to submit if the fields are empty (they don't contain non-digits or non-spaces). You'll need to add a test for that.
function regexTest(form) {
// Get values when the function is called, not before
var pitch = form.pitchfork.value;
var chisel = form.chisels.value;
var saw = form.saw.value;
// Test for anything that's not a space or digit
// var format = /^(\s*|\d+)$/;
var format = /[^\s\d]/;
if (format.test(chisel) || format.test(pitch) || format.test(saw)) {
// There must be at least one non-space or non-digit in a field
alert("Repressed Action");
return false;
} else {
alert('Thank you');
// return false anyway for testing
return false;
}
}
<div class="lab">
<form onsubmit="return regexTest(this)">
Chisels: <input type="text" name="chisels" id="chis" size="5"><br>
Saw: <input type="text" name="saw" id="saw" size="5"><br>
Pitchfork: <input type="text" name="pitchfork" id="pitch" size="5"><br>
Customer Name: <input type="text" name="customer name" size="25"><br>
Shipping Address: <input type="text" name="shipping address" size="25">
<br> State:
<select name="states">
<option>Florida</option>
<option>Georgia</option>
<option>Alabama</option>
</select>
<br>
<input type="radio" id="master" name="card" value="master"><label for="master">MasterCard</label>
<input type="radio" id="american" name="card" value="american"><label for="american">American Express</label>
<input type="radio" id="visa" name="card" value="visa"><label for="visa">Visa</label>
<br>
<input type="reset" value="Reset">
<div class="lab">
<button>Submit</button>
<button onclick="return false">Cancel</button>
</div>
Hopefully this gets you to the next step.
I am new to web development and I am trying to create a simple form validation using javascript/jquery.
I drafted a simple form very similar to what I have that looks like this:
<form>
<input class="price" type="text" />
<br />
<input class="price" type="text" />
<br />
<input class="price" type="text" />
<br />
<input class="price" type="text" />
<br />
<button type="submit" onclick='return validateSubmit();'>Save</button>
</form>
What I want to happen is when the user clicks the submit button, it will check every input box if it contains a valid number (price) before it allows the submit, if one or more of the input box is invalid, it will be highlighted with an alert error "Invalid inputs on highlighted textboxes" or something like that. After couple of searches this is what I have in my script:
var validateSubmit = function () {
var inputs = $('.price');
var errors = 'False';
for (var i = 0; i < inputs.length; i++) {
if (isNaN(inputs[i].value)) {
$('.price')[i].focus();
}
errors = 'True';
}
if (errors == 'True') {
alert('Errors are highlighted!');
return false;
}
return true;
};
I understand what is wrong with what Ive done but I dont know how to fix it.
I know that we can only focus() 1 element at a time but I wanted to have some effect that it highlights the inputboxes with invalid characters.
Please tell me how to do it or if there's a better approach can you show me some examples. I saw bootstrap has some css effects for this focus but I dont know how to implement it. Thank you!
You can add a class to the inputs with bad values. The class can add a border for example.
var validateSubmit = function () {
var inputs = $('.price');
var errors = 'False';
for (var i = 0; i < inputs.length; i++) {
if (isNaN(inputs[i].value)) {
$(inputs[i]).addClass('error');
errors = 'True';
} else {
$(inputs[i]).removeClass('error');
}
}
if (errors == 'True') {
alert('Errors are highlighted!');
return false;
}
return true;
};
.error {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input class="price" type="text" />
<br />
<input class="price" type="text" />
<br />
<input class="price" type="text" />
<br />
<input class="price" type="text" />
<br />
<button type="submit" onclick='return validateSubmit();'>Save</button>
</form>
First, I think you should clean up your HTML. For example, it is always a good idea to give an id attribute to your form tags to reference them. Also, someone correct me if I am wrong, you won't be submitting any values without giving a name attribute to your input fields.
<form id="price-form" action="" method="get">
<input name="price[]" type="text" value="" class="price" />
<br />
<input name="price[]" type="text" value="" class="price" />
<br />
<input name="price[]" type="text" value="" class="price" />
<br />
<input name="price[]" type="text" value="" class="price" />
<br />
<button type="submit">Save</button>
</form>
Now, since you are using jQuery, why not utilize its methods such as on() and .each() ?
$(function() {
$('#price-form').on('submit', function(e) {
// this variable acts as a boolean, so might as well treat it as a boolean
var errors = false;
// remove previous errors
$('.price').removeClass('error');
// check each input for errors
$('.price').each(function() {
if (isNaN(this.value)) {
$(this).addClass('error');
errors = true;
}
});
// alert if there are any errors
if (errors) {
alert('Errors are highlighted!');
e.preventDefault(); // stop submission
}
});
});
In your CSS, you could do
.error {
border: 2px solid #a00;
}
I am having a problem with my math function below. The depreciationFee variable adds up correctly, but for some odd reason the financeFee variable does not. I am trying to calculate the monthly lease payment of a vehicle. Whenever I submit the numbers for financeFee it shows two number appended to each other rather than added together. Is there a reason the numbers aren't adding up correctly?
$(".submit").click(function() {
function calculateLease() {
var capitalCost = $(".capital-cost").val();
var downPayment = $(".down-payment").val();
var residualCost = $(".residual-cost").val();
var monthTerm = $(".month-term").val();
var moneyFactor = $(".money-factor").val();
var depreciationFee = (((capitalCost - downPayment) - residualCost) / monthTerm);
// THIS IS THE ONE THAT DOESN'T WORK
var financeFee = ((capitalCost - downPayment) + residualCost);
alert(financeFee);
}
calculateLease();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="lease-calculator-container">
<h3>LEASE CALCULATOR</h3>
<form method="get">
<input type="text" class="capital-cost" placeholder="MSRP" />
<br />
<input type="text" class="down-payment" placeholder="DOWN PAYMENT" />
<br />
<input type="text" class="residual-cost" placeholder="RESIDUAL" />
<br />
<input type="text" class="month-term" placeholder="TERM IN MONTHS" />
<br />
<input type="text" class="money-factor" placeholder="MONEY FACTOR" />
<br />
</form>
<input type="submit" class="submit" value="CALCULATE" />
<div class="monthly-cost"></div>
<div class="total-cost"></div>
</div>
Do a parseInt(value,10) for intergers or parseFloat(value) for float.
JavaScript appends the values if the data type is not a number.
I am trying to make a sign-up form that will do client-side validation (check the correct layout of email and matching passwords) before sending any data to the server. I have been having trouble checking to see if the email is in the correct form. I can't get the if(email.indexOf(#))to work correctly. I think I misused the .indexOf()
This is my JavaScript:
function sign_check() {
var email = document.getElementById("sign_email").value;
var user = document.getElementById("sign_user").value;
var pass = document.getElementById("sign_pass").value;
var passcon = document.getElementById("sign_confirm").value;
if(pass !== passcon){
document.getElementById("sign_alert").innerHTML="The passwords do not match"
}
//This part determines whether or not to send the data to the server
if(email.length >= 7){
if(email.indexOf("#")){
if(user.length >= 1){
if(pass.length >= 1){
if(passcon.length >= 1){
if(pass === passcon){
alert("All of the requirements have been met")
}
}
}
}
}
}
}
And this is my html:
<h1 id="pop_up" class="pop_up">Sign Up</h1>
<form id="sign_up" class="sign_up">
<label id="alert_s1" class="alert"> <br /> </label>
<input id="sign_email" class="sign" type="text" placeholder="Email" name="sign_email" /><br />
<label id="alert_s2" class="alert"> <br /> </label>
<input id="sign_user" class="sign" type="text" placeholder="Username" name="sign_user" /><br />
<label id="alert_s3" class="alert"> <br /> </label>
<input id="sign_pass" class="sign" type="text" placeholder="Password" name="sign_pass" /><br />
<label id="alert_s4" class="alert"> <br /> </label>
<input id="sign_confirm" class="sign" type="text" placeholder="Confirm Password" name="sign_confirm" />
</form>
<p id="sign_alert" class="alert"></p>
<button onclick="sign_check()">Submit</button>
Already have an acount? Click here to log in.
</div>
First, your method to validate the email is not very accurate :) Besides that, you're using indexOf incorrectly. Use this instead.
if(email.indexOf("#") != -1 )
You used double quotes "" instead of '' in the ('#'). That should make it work. And === actually works too. The quotation marks were all you needed to change. I hope this helps!
I am experimenting with a form that has a text field and a check box. I am a designer and not a developer. I have successfully gotten the text box to Validate, but I have pasted in code for the checkbox, which for some reason either cancels out the validation or returns an error at the paypal server. Can anyone suggest a few lines of code to validate the checkbox "terms"? The textbox is called "os0"
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top" id="myForm" onSubmit="return validateForm()" >
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="AXNKKDCZLVHM4">
<table width="100%" border="0">
<tr>
<th scope="row"><input type="hidden" name="on0" value="Your RCEH Account Number:" />
Your RCEH Account Number:
</th>
<td>
<input type="text" name="os0" maxlength="200" />
</td>
</tr>
<tr>
<th scope="row"> </th>
<td><label>
<input type="checkbox" name="terms" id="terms" />
Agree to terms and conditions</label>
</td>
</tr>
</table>
<input type=submit value="Proceed to secure server">
<img alt="" border="0" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1">
</form>
</div>
</div>
<script>
function validateForm() {
var x=document.forms["myForm"]["os0"].value;
if (x==null || x==""){
alert("RCEH account number must be filled out");
return false;
}
}
</script>
Assuming that you only want your checkbox to be checked, below there is the code you need, and this is a working JSFiddle.
function validateForm() {
var form = document.getElementById("myForm"); //get the form element via ID
if (form.os0.value == "")
{
alert("RCEH account number must be filled out");
return false;
}
if (!form.terms.checked) { // checks if the checkbox called "terms" is checked; if it is not, alerts a message and return false
alert("Terms must be read and approved");
return false;
}
return true; //if everything is okay, return true and submit the form
}