How can I validate with javascript and then submit data with php? - javascript

<button type="button" onclick="submitForm()">Submit</button>
When I press this button it runs a javascript validation function that returns true or false based on whether some data is formatted properly.
What I need to do next is: if true submit the validated data to mySql database using a php script.
I am stumped at how I can accomplish this. I hope I am clear. Thanks.
Also, I can't use ajax.

In the php file you can do all the mysql verifications needed.
The submit can be something like this
<form action="update.php" method="post"> <button type="submit" onclick="return submitForm()">Submit</button> </form>
Notice the return in the function call.
The verification is returning false when validation fails.
function submitForm() {
if(validation) { // fails
alert("your message");
return false;
}
}

Do your button type to submit and send to the form ex like this
<form action="update.php" method="post">
<button type="submit" onclick="submitForm()">Submit</button>
</form>
In index.php file check the mysql validation
You have missed the return in the function call. Try with
<button type="button" onclick="return submitForm()">Submit</button>
where you are returning false when validation fails.
function submitForm() {
if(validation) // fails
{
alert("your message");
return false;
}
}

use type = "submit" instead of button. try with -
<button type="submit" onclick="submitForm()">Submit</button>
js validation
function submitForm() {
//your validation codes
//if validates
return true
//else
return false;
}
if validation succeeds the the form will be submitted else will not be submitted.

HTML:
<button type="button" onclick="submitForm()">Submit</button>
JS:
function submitForm() {
if(){ //condition to validate
return true;
}else{
return false;
}
}
Also (as a suggestion) you can add a specific function to validate each type of value so then just call it in your function submitForm() by those types

You have missed the return in the function call. Try with
<button type="button" onclick="return submitForm()">Submit</button>
^
where you are returning false when validation fails.
function submitForm() {
if(validation) // fails
{
alert("your message");
return false;
}
}

Do your button type to submit and send to the form
ex like this
<form action="index.php" method="post">
....
<button type="submit" onclick="submitForm()">Submit</button>
</form>
In index.php file check the mysql validation
Hope this will help you

You need to add more detail from your html page. For instance the html form itself.
However just a hunch of what you are looking for.... you can use the folling command in your submitForm() function:
document.getElementById("myForm").submit();

We can't much help if we don't see your code. But in a nutshell you would submit the form by
document.getElementById('formId').submit();

What I need to do next is:
1->perform form.submit()
2->send all data's to database from your action file (action="action.php")

document.getElementById("form").submit()

<script type='text/javascript'>
function formValidator(){
// Make quick references to our fields
var firstname = document.getElementById('firstname');
var addr = document.getElementById('addr');
var zip = document.getElementById('zip');
var state = document.getElementById('state');
var username = document.getElementById('username');
var email = document.getElementById('email');
// Check each input in the order that it appears in the form!
if(isAlphabet(firstname, "Please enter only letters for your name")){
if(isAlphanumeric(addr, "Numbers and Letters Only for Address")){
if(isNumeric(zip, "Please enter a valid zip code")){
if(madeSelection(state, "Please Choose a State")){
if(lengthRestriction(username, 6, 8)){
if(emailValidator(email, "Please enter a valid email address")){
return true;
}
}
}
}
}
}
return false;
}
function notEmpty(elem, helperMsg){
if(elem.value.length == 0){
alert(helperMsg);
elem.focus(); // set the focus to this input
return false;
}
return true;
}
function isNumeric(elem, helperMsg){
var numericExpression = /^[0-9]+$/;
if(elem.value.match(numericExpression)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
function isAlphabet(elem, helperMsg){
var alphaExp = /^[a-zA-Z]+$/;
if(elem.value.match(alphaExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
function isAlphanumeric(elem, helperMsg){
var alphaExp = /^[0-9a-zA-Z]+$/;
if(elem.value.match(alphaExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
function lengthRestriction(elem, min, max){
var uInput = elem.value;
if(uInput.length >= min && uInput.length <= max){
return true;
}else{
alert("Please enter between " +min+ " and " +max+ " characters");
elem.focus();
return false;
}
}
function madeSelection(elem, helperMsg){
if(elem.value == "Please Choose"){
alert(helperMsg);
elem.focus();
return false;
}else{
return true;
}
}
function emailValidator(elem, helperMsg){
var emailExp = /^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
if(elem.value.match(emailExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
</script>
<form onsubmit='return formValidator()' >
First Name: <input type='text' id='firstname' /><br />
Address: <input type='text' id='addr' /><br />
Zip Code: <input type='text' id='zip' /><br />
State: <select id='state'>
<option>Please Choose</option>
<option>AL</option>
<option>CA</option>
<option>TX</option>
<option>WI</option>
</select><br />
Username(6-8 characters): <input type='text' id='username' /><br />
Email: <input type='text' id='email' /><br />
<input type='submit' value='Check Form' />
</form>

Related

Html Form If statement in OnSubmit Field

I'm fairly new to html/php/js and I'm running into an issue when conditionally submitting my form. Basically, what Im trying to do is have it where the confirm('Do you want to submit this form?') function only shows up if every field has a value entered (the checkform() function). If both are true, then the form will submit. Any help would be greatly appreciated, thanks!
<script type="text/javascript">
function checkform()
{
var myForm=document.frmhot;
if(myForm.status.value==""){
alert("Please select a timeframe status.");
return false;
myForm.status.focus();
}
if (myForm.line.value==""){
alert("Please select a line.");
return false;
}
if(myForm.reason.value==""){
alert("Please select a reason code.");
return false;
}
if(myForm.partnum.value==""){
alert("Please enter a part number.");
return false;
}
if(myForm.badgescan.value==""){
alert("Please enter a badge number.");
return false;
}
return true;
}
</script>
<form method="post" action="newhotpartgenerate.php" name="frmhot"
onclick="if(checkform();){
confirm('Do you want to submit the form?');
}
>
<input class="button_text" type="submit" value="Submit" name="submit" onclick= "checkform();" />
</form>
Complete working solution with corrections and tweaks for IE compatibility to a certain extend.
<script>
function checkform(evt) {
var myForm = document.frmhot;
var condition = true;
if(myForm.status.value==""){
alert("Please select a timeframe status.");
myForm.status.focus();
condition = false;
}
if (myForm.line.value==""){
alert("Please select a line.");
condition = false;
}
if(myForm.reason.value==""){
alert("Please select a reason code.");
condition = false;
}
if(myForm.partnum.value==""){
alert("Please enter a part number.");
condition = false;
}
if(myForm.badgescan.value==""){
alert("Please enter a badge number.");
condition = false;
}
if(condition){ condition = confirm('Do you want to submit the form?'); }
if(!condition) {
if(evt.preventDefault) { event.preventDefault(); }
else if(evt.returnValue) { evt.returnValue = false; }
else { return false; }
}
}
</script>
<form method="post" action="newhotpartgenerate.php" name="frmhot" onsubmit="checkform(event)">
<input type="text" name="status"/>
<input type="text" name="line"/>
<input type="text" name="reason"/>
<input type="text" name="partnum"/>
<input type="text" name="badgescan"/>
<input class="button_text" type="submit" value="Submit"/>
</form>
You have the right idea, just extract your code into its own function and then call that in the onclick.
Add this function:
function checkAndConfirm() {
if(checkform()) {
if (confirm('Do you want to submit the form?')) {
// submit the form
}
}
And then call it from the onclick attribute:
<form method="post" action="newhotpartgenerate.php" name="frmhot" onclick="checkAndConfirm()">

Get Error for submit button before send data to Server side(php)

i have a text box or input to save Phone number, i want that Users Can Only be able to Enter 11 Numbers and Just can accept Numbers Not Characters.
how Check and show message.
how this is possible in client side Like JavaScript And then Sending To Server Side.
my code that it`s Incorrect:
<script language="JavaScript" type="text/javascript">
function code(input){
if(input.length != "11"){
//return false;
alert("Enter a Valid Phone Number");
} else {
return true;
}
}
and in submit section:
<input type=submit border=0 value=" " Onclick=code(getElementById("Phone").value) />
Thanks
you should use return false after alert in validate condition, try this code
function code(input){
if(input.length != "11"){
alert("Enter a Valid Phone Number");
return false;
}
}
UPDATE
If you want to accept only 11 number then try with RegEx
function code(input){
if(input.match(/^[0-9]{11}$/)){
return true;
}
alert("Enter a Valid Phone Number");
return false;
}
submit button change Onclick to onClick with quote and use document.getElementById("Phone").value instead of getElementById("Phone").value
<input type=submit border=0 value=" "
onClick='return code(document.getElementById("Phone").value)' />
<script>
function code(inputd)
{
var phoneno = /^\d{11}$/;
if(inputd.match(phoneno))
{
return true;
}
else
{
alert("error");
return false;
}
}
</script>
<form>
<input type="text" id='Phone'>
<input type="submit" onclick=return code(document.getElementById("Phone").value);>
</form>
Please try this hope it is helpful.
Use jQuery Keypress event to disallow user to enter any character other than number (0-9).
jQuery(function(){
jQuery("#Phone").keypress(function(){
var value = jQuery(this).val();
value = value.replace(/[^0-9]+/g, '');
jQuery(this).val(value);
});
});
Now, in your validation script, check the length
function code(input){
if(input.length != "11"){
alert("Enter a Valid Phone Number");
return false;
}
else {
return true;
}
}
Using jquery is very easy. Try with:
<input type='text' id='phoneNum' border=0 value="" />
<input type='submit' id='submitBtn' border=0 value="" />
<script language="JavaScript" type="text/javascript">
$('#submitBtn').click(function(){
var phoneNum = $('#phoneNum').val();
code(phoneNum);
// other code
});
function code(input){
if(input.length != "11"){
//return false;
alert("Enter a Valid Phone Number");
} else {
return true;
}
}
</script>

Form validation problems

I have a very strange problem. Inside form I have hidden input with value -1 and input field for username.
<form action="" method="POST" name="login" onSubmit="return Validate()">
<input type="text" id="username"/>
<input type="hidden" id="available" value="-1"/>
< input type="submit" value="Send"/>
</form>
On submit function Validate() checks value of username input which mustn't be empty, and Validate() also checks value of available input which mustn't be valued -1.
function Validate(){
var a=document.getElementById("username").value;
var b=document.getElementById("available").value;
if(a=="" || a==null)
{
alert("Username cannot be empty");
return false;
}
else if(b<0)
{
alert("Form isn't finished");
return false;
}
else
{
return true;
}
}
Problem is that Validate() works only if one condition is evalueted. If function Validate() contains only 1 var(a or b) and 1 if order(without else if) it works correctly. But when I put it like this, when Validate uses a and b variables and if, else if conditional order it won't work. Really od.. Thanks in advance...
In this case it works:
function Validate(){
var a=document.getElementById("username").value;
if(a=="" || a==null)
{
alert("Username cannot be empty");
return false;
}
else
{
return true;
}
}
<input type="hidden" id="available" value="-1"/>
Here the value is of string dataType. Whereas
else if(b<0) //b is string dataType
Hence it failed. so change it as
var b= Number(document.getElementById("available").value);
Try like this
HTML:
<form action="" method="POST" name="login">
<input type="text" id="username" />
<input type="hidden" id="available" value="1" />
<input type="button" value="Send" onClick="return Validate()" />
</form>
JS:
function Validate() {
var a = document.getElementById("username").value;
var b = Number(document.getElementById("available").value);
if (a == "" || a == null) {
alert("Username cannot be empty");
return false;
} else if (b < 0) {
alert("Form isn't finished");
return false;
} else {
document.login.submit(); //dynamically submit the form
}
}
If you are wanting to get error notifications for each input don't use if/else here, use multiple if's and set your errors
function validate(){
var a=document.getElementById("username").value;
var b=document.getElementById("available").value;
var errors = [];
if(a=="" || a==null){
errors.push("Invalid username");
}
if(b<0 || isNaN(b)){
errors.push("Invalid available value");
}
if(errors.length>0) {
//do something with errors (like display them
return false;
}
}
Using the else if one of them evaluates to true it will skip the others. For instance if the first one is empty or null then it will do that block and skip the others.
I was testing your code for IE and Firefox and it work. Just add parseInt when you get the value of var b.
var b= parseInt(document.getElementById("available").value);

Validation values

I'm trying to validate my values for alphabets and numberic as well as checking from database. I have created a function of validation and declaring my onclick button with validation function.
Function:
<script>
function validate()
{
var StudentID= document.getElementById('StudentID').value;
var StudentName = document.getElementById('StudentName').value;
var StudentAdd = document.getElementById('StudentAdd').value;
if(StudentID.length ==0 || StudentName.length ==0)
{
alert("Please do not leave any blanks");
return false;
}
else
{
if(isNumeric(StudentID))
{ alert("correct") }
else { alert("Numbers only!"); return false;}
alert("Correct correct");
}
return true;
}
</script>
Sample Form:
<form id="Student" name="Student" method="post" action="nextpage.php">
<input name="StudentID" type="text" id="StudentID" value="<?php echo $StudentID?>"/>
<input name="StudentName" type="text" id="StudentName" value="<?php echo $StudentName?>"/>
<input name="StudentAdd" type="text" id="StudentAdd" value="<?php echo $StudentAdd?>"/>
<input type="submit" name="submit" value="Submit" onclick="return validate();"/>
</form>
I have already declared return validate function instead of calling my nextpage.php. But nothing popup for any alert. Kindly advise.
Thanks
Try including your scripts after the body tag to make sure it only references elements after it has already been loaded. Then put return true inside the else statement.
function validate()
{
var StudentID= document.getElementById('StudentID').value;
var StudentName = document.getElementById('StudentName').value;
var StudentAdd = document.getElementById('StudentAdd').value;
if(StudentID.length ==0 || StudentName.length ==0)
{
alert("Please do not leave any blanks");
return false;
}
else
{
if(isNumeric(StudentID))
{ alert("correct") }
else { alert("Numbers only!"); return false;}
alert("Correct correct");
return true;
}
}
Instead of the submit button's onclick, move the function to the form's onsubmit, like:
<form onsubmit="validate()" ...>
For the part of the 'if' statement that returns true you may run into some issues with the alerts() as the browser will be trying to submit the form, but over all it should work.
There is no isNumeric() function in JavaScript (I get Uncaught ReferenceError: isNumeric is not defined). You have to create it on your own: Validate decimal numbers in JavaScript - IsNumeric()

Post Method Not giving Alerts like planned?

<form action="" method="post">
<div align="center"><legend>Add a Code</legend>
<label for="code"></label>
<input type="text" name="code" id="code" maxlength="10" />
<input type='button'
onclick=
"isAlphanumeric(document.getElementById('code'),'Your Submission Contained Invalid Characters');
isBadPhrase(document.getElementById('code'), 'Please Enter A Correct Friend Code!');"
value='Check Field' />
function isAlphanumeric(elem, helperMsg){
var alphaExp = /^[0-9a-zA-Z]+$/;
if(elem.value.match(alphaExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
function isBadPhrase(elem,helperMsg){
var badPhrase=/EPW|ESW|\s/;
if (elem.value.match(badPhrase)){
alert(helperMsg);
elem.focus();
return false;
}else{
return true;
}
}
What is wrong here?
You aren't returning anything from your handler. You need to return a value (true/false) from the handler, especially if you want to stop the default. Note -- I'd also change the name of the "BadPhrase" method to "GoodPhrase" so that it matches the sense of the return value.
script:
function isAlphanumeric(elem, helperMsg){
var alphaExp = /^[0-9a-zA-Z]+$/;
if(elem.value.match(alphaExp)){
return true;
} else {
alert(helperMsg);
elem.focus();
return false;
}
}
function isGoodPhrase(elem,helperMsg){
var badPhrase=/EPW|ESW|\s/;
if (elem.value.match(badPhrase)){
alert(helperMsg);
elem.focus();
return false;
} else {
return true;
}
}
function checkInput(id) {
return isAlphanumeric(document.getElementById(id),'Your Submission Contained Invalid Characters')
&& isGoodPhrase(document.getElementById(id), 'Please Enter A Correct Friend Code!');
}
html:
<input type='button' onclick="return checkInput('code');" value='Check Field' />
EDIT:
If you do the validation on form submit it will run regardless of how the form is submitted. You can add it as a onsubmit handler in the form tag, like you did for the click handler of the button. The button should probably be a submit button if it is supposed to trigger form submission.
Note: my preference would be to add the handlers via javascript rather than in the tag, but that's outside the scope of the question. I'd also probably use a framework rather than raw javascript, but that's also outside the scope.

Categories

Resources