I'm using a submit button for a form and the javascript should tell me if any field is empty.. But despite using the onclick attribute , nothing's happening.. There's ablock of PHP code which refuses to store the data. I'm a beginner to PHP and Javascript so any ideas?
<script language="javascript">
function valid()
{
var a=document.form2.i1.value;
var b=document.form2.pas.value;
var c=document.form2.pas1.value;
var d=document.form2.n1.value;
var e=document.form2.a1.value;
var f=document.form2.r1.value;
var g=document.form2.pin1.value;
var h=document.form2.phno1.value;
var i=document.form2.u1.value;
var j=document.form2.email1.value;
if(a!="y")
{
alert("Please accept the terms and conditions before registering.");
return false;
}
else if(d=="")
{
alert("Name required.");
return false;
}
else if(e=="")
{
alert("Age required.");
return false;
}
else if(e<18)
{
alert("You have to be atleast 18 to register.");
return false;
}
else if(f="")
{
alert("Gender required.");
return false;
}
else if(g=="" || isNan(g))
{
alert("Valid pincode required.");
return false;
}
else if(h==""|| isNan(h))
{
alert("Valid phone number required.");
return false;
}
else if(i=="")
{
alert("Username required.");
return false;
}
else if(j=="")
{
alert("Email required.");
return false;
}
else if(b=="" || c=="")
{
alert("Password required.");
return false;
}
else if(b!=c)
{
alert("Please make sure the passwords are identical.");
return false;
}
return true;
}
</script>
This is the statement I used to call it:
<div id="apDiv3"><input name="reg1" type="submit" id="login-submit" value="Register" onclick="return valid()"/></div>
This is the PHP code I used to create the form:
<?php
if(isset($_POST['reg1']))
{
$name=$_POST['n1'];
$age=$_POST['a1'];
$gen=$_POST['r1'];
$phno=$_POST['phno1'];
$email=$_POST['email1'];
$pin=$_POST['pin1'];
$user=$_POST['u1'];
$pas=$_POST['pass'];
$pas1=$_POST['pass1'];
$i=$_POST['i1'];
$connection=mysqli_connect("localhost","root","");
if (!$connection) {
die("Database connection failed: " . mysqli_error($connection));
}
$db_select = mysqli_select_db($connection, "vinay");
if (!$db_select) {
die("Database selection failed: " . mysqli_error($db_select));
}
$q="insert into reg values('0','$name','$age','$gen','$phno','$email','$pin','$user','$pas')";
mysqli_query($q) or die(mysqli_error($q));
if(mysqli_affected_rows()>0)
{
header("location:index.php");
}
}
?>
Why do you want to use JavaScript when HTML5 already has attributes for this purpose. Use the pattern and the required attributes.
For reference see: http://www.w3schools.com/html/html5_form_attributes.asp
Related
I have the form values stored in javascript variables now i tried to validate in javascript
I want to know is this the right format which i'm trying to implement
function validate()
{
//getting values from the form in a variable
<!--now validation starts-->
if(condition1==true)
{
if(condition2==true)
{
if(condition3==true)
{
statement1;
}
else
{
statement2;
}
}
else
{
statement3;
}
}
else
{
statement4;
}
}
try :
if (!condition1) {
statement4;
} else if (!condition2) {
statement3;
} else if (!condition3) {
statement2;
} else {
statement1;
}
to validate forms, you do not need to have nested if.
function validate(){
if(b=="" || b==null){
alert("Please enter your city");
return false;
}
if(a=="" || a==null){
alert("Please enter your address");
return false;
}
return true;
}
I am trying to validate a form without using html5 validation as an exercise for a class, but I can't figure it out for the life of me.
I want to have an alert message pop up if the email and/or name is not valid/empty.
I have gotten to the point where the alert will pop up form the email OR the name field, depending which is first in the onsubmit function.
Any ideas would be greatly appreciated!
document.getElementById("frmContact").onsubmit = function() {
var inputEmail= document.getElementById("email").value,
emailPattern = new RegExp("^[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$");
if (inputEmail==="") {
alert("Please enter your email.")
return false;
} else if (!emailPattern.test(inputEmail)){
alert("Please enter a valid email address.");
return false;
} else {
return true;
};
var inputName= document.getElementById("name").value,
namePattern = new RegExp("^[A-Za-z]+$");
if (inputName==="") {
alert("Please enter your name.")
return false;
} else if (!namePattern.test(inputName)){
alert("Please enter a valid name.");
return false;
} else {
return true;
};
};
You return after the first one is validated, so the second field is never checked. Instead, have a local variable that is set to true by default, and set to false of either of the fields fail validation, and return it at the end.
var valid = true;
// ...
if(inputEmail==="") {
alert("Please enter your email.");
valid = false;
// ...
return valid;
};
Maybe this doesn't work but the concept could be something like this...
document.getElementById("frmContact").onsubmit = function() {
var inputEmail= document.getElementById("email").value,
emailPattern = new RegExp("^[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$"),
error = [],
i = 0;
if (inputEmail==="") {
error.push("Please enter your email");
} else if (!emailPattern.test(inputEmail)){
error.push("Please enter a valid email address.");
}
var inputName= document.getElementById("name").value,
namePattern = new RegExp("^[A-Za-z]+$");
if (inputName==="") {
error.push("Please enter your name.")
} else if (!namePattern.test(inputName)){
error.push("Please enter a valid name.");
}
if(typeof error !== 'undefined' && error.length > 0){
alert("you submit the form correctly");
} else {
for(i = 0; i < error.length; i + 1){
alert(error[i]);
}
}
};
I have this email form validation script:
<script type="text/javascript" language="javascript">
function validateForm(thisform){
if(thisform.Name.value=="") {
alert("Ooouuupppsss... You did not enter your Name.");
thisform.Name.focus();
return false;
}
if(thisform.Email.value=="") {
alert("Ooouuupppsss... You did not enter a valid Email Address.");
thisform.Email.focus();
return false;
}
if(thisform.Subject.value=="") {
alert("Ooouuupppsss... You did not enter your Subject.");
thisform.Subject.focus();
return false;
}
if(thisform.Message.value=="") {
alert("Ooouuupppsss... You did not enter your Message.");
thisform.Message.focus();
return false;
}
}</script>
Can someone please tell me what do I have to add in this script in order to make the users enter a valid email address. Also I would like in the rest of the fields to make users to enter text (not links).
I've tried to add different pieces of code which I found on different websites but they did not work and this is because I am not sure if I am adding them right.
Thank you for reading my request.
All the best,
Andi
For e-mail checking you can use following code in else part after checking if e-mail is empty
function validateForm(){
var email = document.getElementById("email").value;
var emailRegEx = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (email.search(emailRegEx) == -1) {
alert("e-mail is not valid");
return false;
}
}
and for url with same logic you can use following regular expression
var urlRegEx = /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+#)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+#)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%#.\w_]*)#?(?:[\w]*))?)/;
following is a working example based on your work, you can improve this code it is only for showing you how it should be.
function validateForm(thisform){
if(thisform.Name.value=="") {
alert("Ooouuupppsss... You did not enter your Name.");
thisform.Name.focus();
return false;
}
else{
var name = thisform.Name.value;
if (!checkURL(name)) {
alert("name cannot be a url");
return false;
}
}
if(thisform.Email.value=="") {
alert("Ooouuupppsss... You did not enter a valid Email Address.");
thisform.Email.focus();
return false;
}
else{
var email = thisform.Email.value;
var emailRegEx = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (email.search(emailRegEx) == -1) {
alert("e-mail is not valid");
return false;
}
}
if(thisform.Subject.value=="") {
alert("Ooouuupppsss... You did not enter your Subject.");
thisform.Subject.focus();
return false;
}
else{
if (!checkURL(thisform.Subject.value)) {
alert("subject cannot contain a url");
return false;
}
}
if(thisform.Message.value=="") {
alert("Ooouuupppsss... You did not enter your Message.");
thisform.Message.focus();
return false;
}
else{
if (!checkURL(thisform.Message.value)) {
alert("message cannot contain a url");
return false;
}
}
}
function checkURL(url){
var urlRegEx = /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+#)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+#)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%#.\w_]*)#?(?:[\w]*))?)/;
if (url.search(urlRegEx) == -1) {
return true;
}
return false;
}
See this post for regex urls: regular expression for url
See this post for email validation: Validate email address in JavaScript?
See this for X browser event listening, if would use jQuery, ie8 uses attach see this: Javascript add events cross-browser function implementation: use attachEvent/addEventListener vs inline events
I would recommend looping through the form inputs, and checking if its email and if its not run the regex against the link.
(function(){
var validateForm = function(form){
var errors = [], inputs = form.getElementsByTagName('input');
for(var input = 0; input<inputs.length; input++){
var currentInput = inputs[input];
if(currentInput.value === ''){
// handle attributes here for error message, push error message
if(currentInput.attribute('name') === 'email'){
// handle email
// push error message
}
}
}
return errors;
}
var contactForm = document.getElementById('contact');
contactForm.addEventListener('submit', function(e){
var errorMessages = validateForm(contactForm);
if(errorMessages.length === 0){
} else {
e.preventDefault() // stop the form from submitting
// handle your messages
}
}
}());
I'm in the middle of coding CAPTCHA in JavaScript, and I'm trying to get the validation for a contact form to work properly. I'm almost there, the form won't be submitted until the CAPTCHA text-field is entered, but the problem is I'm still getting an error message when I entered the CAPTCHA code correctly.
<script>
function ValidateContactForm()
{
var name = document.ContactForm.name;
var phone = document.ContactForm.phone;
var code = document.ContactForm.code;
if (name.value == "")
{
window.alert("Please enter your name.");
name.focus();
return false;
}
if (phone.value == "")
{
window.alert("Please enter a valid phone number..");
phone.focus();
return false;
}
if (code.value == "")
{
window.alert("Please enter the code as displayed on screen.");
code.focus();
return false;
}
else if (code.value != "")
{
window.alert("Your code does not match. Please try again.");
code.focus();
return false;
}
else {
return true;
}
return true;
}
</script>
Any help would be greatly appreciated. Thanks.
Check this lines, the problem is here:
if (code.value == "")
{
window.alert("Please enter the code as displayed on screen.");
code.focus();
return false;
}
else if (code.value != "")
{
window.alert("Your code does not match. Please try again.");
^^^^^^^^^^^^^
code.focus();
^^^^^^^^^^^^^
return false;
^^^^^^^^^^^^^
}
else {
return true;
}
This code will return false every time.
Here is my Javascript formvalidator function:
function companyName() {
var companyName = document.forms["SRinfo"]["companyName"].value;
if (companyName == ""){
return false;
} else {
return true;
}
}
function companyAdd() {
var companyAdd1 = document.forms["SRinfo"]["companyAdd1"].value;
if (companyAdd1 == ""){
return false;
} else {
return true;
}
}
function companyCity() {
var companyCity = document.forms["SRinfo"]["companyCity"].value;
if (companyCity == ""){
return false;
} else {
return true;
}
}
function companyZip() {
var companyZip = document.forms["SRinfo"]["companyZip"].value;
if (companyZip == ""){
return false;
} else {
return true;
}
}
function enteredByName() {
var enteredByName = document.forms["SRinfo"]["enteredByName"].value;
if (enteredByName == ""){
return false;
} else {
return true;
}
}
function dayPhArea() {
var dayPhArea = document.forms["SRinfo"]["dayPhArea"].value;
if (dayPhArea == ""){
return false;
}
}
function dayPhPre() {
var dayPhPre = document.forms["SRinfo"]["dayPhPre"].value;
if (dayPhPre == ""){
return false;
} else {
return true;
}
}
function dayPhSub() {
var dayPhSub = document.forms["SRinfo"]["dayPhSub"].value;
if (companyAdd1 == ""){
return false;
} else {
return true;
}
}
function validateForm() {
if (companyName() && companyAdd() && companyCity() && companyZip() && enteredByName() && dayPhArea() && dayPhPre() && dayPhSub()) {
return true;
} else {
window.alert("Please make sure that all required fields are completed.");
document.getElementByID("companyName").className = "reqInvalid";
companyName.focus();
return false;
}
}
Here are all of my includes, just in case one conflicts with another (I am using jquery for their toggle()):
<script type="text/javascript" src="formvalidator.js"></script>
<script type="text/javascript" src="autoTab.js"></script>
<?php
require_once('mobile_device_detect.php');
include_once('../db/serviceDBconnector.php');
$mobile = mobile_device_detect();
if ($mobile) {
header("Location: ../mobile/service/index.php");
if ($_GET['promo']) {
header("Location: ../mobile/service/index.php?promo=".$_GET['promo']);
}
}
?>
<script src="http://code.jquery.com/jquery-1.7.1.js"></script>
Here is my form tag with the function returned onSubmit:
<form method="POST" action="index.php" name="SRinfo" onsubmit="return validateForm();">
The validation works perfectly, I tested all fields and I keep getting the appropriate alert, however after the alert the form is submitted into mysql and sent as an email. Here is the code where I submit my POST data.
if($_SERVER['REQUEST_METHOD']=='POST') {
// Here I submit to Mysql database and email form submission using php mail()
It would seem to me that this line is likely blowing up:
companyName.focus();
The only definition I see for companyName is the function. You can't call focus on a function.
This blows up so the return false is never reached.
I would comment out all the code in the validation section and simply return false. If this stops the form from posting then there is an error in the actual code performing the validation. Add each part one at a time until the error is found.
My guess is the same as James suggests that you are calling focus on the function 'companyName'. The line above this seems to be trying to get the element from the document with the same name but you are not assigning this to a variable so that you can call focus on it.