I have a nagging feeling this has been asked, but I'm not sure how to phrase it correctly, so I'll ask here anyway.
I'm writing a simple calculator script (for learning, I'm newbie), and I split it up into two parts - front end form validation with JS and calculation with PHP.
To be more specific, here are the three parts:
HTML (index.php)
<form action = "calculator.php" method = "post">
First number: Input field here
Operator: Drop down
Second number: Input field here
Submit button
</form>
JavaScript (validate.js)
validate() - regex checks that first and second number are all digits
PHP (calculator.php)
Extract first and second number, calculate result, and display on page
Here's my question - I would like to make it such that when the submit button is pressed, the page is passed on to the server ONLY if all regex tests are passed.
Something like:
validate() {
// testing code
...
if first_num_valid == true && second_num_valid == true
redirect to calculator.php
}
How do I do this in Javascript?
Or, if this isn't possible, can you suggest an alternative to this?
Thanks!
EDIT 1: Tried @joe's solution but not sure how to make it work?
$("#calculator").onsubmit(function() {
if (first_valid && second_valid)
return true;
else
return false;
});
I assume @joe was trying to say that the form only submit only if the return value is true, but I tried this, but the form submitted whether or not the values were true?
EDIT 2: For clarification
index.php
<form id = "calculator" action = "./calculation.php" method = "post" >
<table>
<tr>
<td>First number</td>
<td><input type = "text" name = "first_num" id = "first_num"/></td>
</tr>
<tr>
<td>Operator</td>
<td>
<select name = "operator">
<option value = "+" name = "add">+</option>
<option value = "-" name = "minus">-</option>
<option value = "*" name = "multiply">*</option>
<option value = "/" name = "divide">/</option>
</select>
</td>
</tr>
<tr>
<td>Second number</td>
<td><input type = "text" name = "second_num" id = "second_num" /></td>
</tr>
<tr>
<td>
<input type = "submit" name = "submit" id = "submit" onclick = "validate()"/>
</td>
</tr>
</table>
</form>
validate.js
function validate() {
var first_num = $("#first_num").val();
var second_num = $("#second_num").val();
var regex = new RegExp("^[\\d]+$");
var first_valid = regex.test(first_num);
var second_valid = regex.test(second_num);
var alert_string = "";
if (!first_valid && second_valid)
alert_string += "First number invalid!<br />";
else if (first_valid && !second_valid)
alert_string += "Second number invalid!";
else if (!first_valid && !second_valid)
alert_string += "Both numbers invalid!";
if (!first_valid || !second_valid)
alert(alert_string);
$("#calculator").onsubmit(function() {
if (first_valid && second_valid)
return true;
else
return false;
});
}
EDIT 3: Put all code in handler, didn't work?
$("#calculator").on('submit', function() {
var first_num = $("#first_num").val();
var second_num = $("#second_num").val();
var regex = new RegExp("^[\\d]+$");
var first_valid = regex.test(first_num);
var second_valid = regex.test(second_num);
var alert_string = "";
if (!first_valid && second_valid)
alert_string += "First number invalid!";
else if (first_valid && !second_valid)
alert_string += "Second number invalid!";
else if (!first_valid && !second_valid)
alert_string += "Both numbers invalid!";
if (!first_valid || !second_valid)
alert(alert_string);
if (first_valid && second_valid)
return true;
else
return false;
});
-
Have a look for ajax. I'd give you a full answer but it's been done to death.ScottMcGready– ScottMcGready2014年05月16日 18:14:07 +00:00Commented May 16, 2014 at 18:14
-
I stopped after the title. This question came way to often recently. Retracted the vote.Gerald Schneider– Gerald Schneider2014年05月16日 18:20:33 +00:00Commented May 16, 2014 at 18:20
-
The question has been edited to include jquery. That changes a lot!000– 0002014年05月16日 18:24:33 +00:00Commented May 16, 2014 at 18:24
-
@blazonix don't forget to select an answer as "accepted" if your problem was solvedkhaverim– khaverim2014年05月29日 03:57:32 +00:00Commented May 29, 2014 at 3:57
3 Answers 3
Here's an answer for your form validation question.
First, give your form an id so that you can identify it.
<form id="calculator_form" action="calculator.php" method="post">
Then, attach a submit handler for that form. If the submit handler fails, the form will not submit.
document.getElementById('calculator_form').onsubmit = function() {
if (!first_num_valid) {
return false;
}
if (!second_num_valid) {
return false;
}
return true;
}
OK now your question edit has jquery. That changes my answer here.
$("#calculator").on('submit', function() {
if (first_valid && second_valid) {
return true;
}
return false;
});
13 Comments
AJAX! (a basic AJAX call in jQuery)
function validate() {
// testing code
if (yourRegexTest == true) {
$.ajax({
url: "calculator.php?data1=" + jsVar1 + "&data2=" + jsVar2; // ...etc
type: 'GET',
dataType: 'json',
success: function(data) {
// data[0] now carries the php variable $newVar1 (below)
// data[1] now carries $newVar2 (below)
// do stuff with data[0] and data[1];
return false; // do not submit the form. The ajax call does what you want pressing the submit button to effectively do.
}
});
} else { alert('regex check failed');
return false; // do not submit the form. regex check failed.
}
}
calculator.php
<?php
$var1 = $_GET['data1']; $var2 = $_GET['data2'];
$newVar1 = dostuffto($var1);
$newVar2 = dostuffto($var2);
echo json_encode(array($var1,$var2));
?>
Also -- "Here's my question - I would like to make it such that when the submit button is pressed, the page is passed on to the server ONLY if all regex tests are passed."
On the submit button use <input type="submit" id="myID" value="sumbit" onclick="return validate();"/>
When you return a JS function on an onclick event for a submit button as above, the form will not be submitted unless that function returns true. In my example the form never gets "submitted", but rather, the AJAX call is run only if the regex check passes.
AJAX is what you would want to look at to send things asynchronously to PHP. Here is jQuery's API on the subject. Gather your form info, submit it with AJAX, and put in your callback functions to capture what PHP kicks out (which you will use to display to the user on screen).
One side note I would like to offer though is that you do some validation on the server side. It certainly isn't a bad thing to do any validation with JS on the client side, but malicious users can circumvent your validation. My suggestion for validation is to do some basics with JS, but make sure PHP is sanitizing/validating the input properly.
EDIT
I have a version of this you can take a look at that uses native JS (as your question originally started as). You appear to need AJAX, but looking at your question it looks like you wish to simply submit the form. I say this because there seems to be no immediate place in your code where a return value would be delivered.
Anyhow, the basic idea is to get both of your values from your number fields, check them as number, and then submit. Give this a try:
<form id = "calculator" action = "./calculation.php" method = "post" onsubmit="return validate()" >
<table>
<tr>
<td>First number</td>
<td><input type = "text" name = "first_num" id = "first_num"/></td>
</tr>
<tr>
<td>Operator</td>
<td>
<select name = "operator">
<option value = "+" name = "add">+</option>
<option value = "-" name = "minus">-</option>
<option value = "*" name = "multiply">*</option>
<option value = "/" name = "divide">/</option>
</select>
</td>
</tr>
<tr>
<td>Second number</td>
<td><input type = "text" name = "second_num" id = "second_num" /></td>
</tr>
<tr>
<td>
<input type = "submit" name = "submit" id = "submit" />
</td>
</tr>
</table>
</form>
<script type="text/javascript">
function validate()
{
var num1 = document.getElementById('first_num').value;
var num2 = document.getElementById('second_num').value;
if(!isNaN(num1) && !isNaN(num2)) {
alert("Numbers!");
return true;
}
alert("Fail!");
return false;
}
</script>
Hope that helps. I still can stress enough that in a real-life application you should really rely on server side validation of data.