Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have already searched the site and while I found similar issues, I couldn't get the answer I needed, so I am asking now. I need to validate a contact form, the PHP validation is very simple but works on a base level, I want to supplement this with browser validation through JS but it is not working, the JS validation does not trigger or is not correctly coded.
I'm working on this page: http://camp-tags.com/?main_page=contact
Thanks in advance for looking for me.
The function is supposed to loop through and make sure that the 4 elements are not empty, and that both variables for phonenumber and email are formatted correctly. If any flag as false, the error is supposed to be pushed to an array and then all errors output in a single alert.
Below is the code. (updated using the tips given here. No validation at all now.)
*update: I found one glaring error I can not believe I missed. I didn't have a closing tag on the , now that is done, the form will not send unless you input the phone correct but is not validating the rest and no Alert is being issued to advise what is wrong?
JS:
function validateForm(event){
var form1 = document.getElementById("form1"),
phone = document.getElementById("phonenumber").value,
email = document.getElementById("email").value,
name = document.getElementById("name").value,
address = document.getElementById("address").value,
tomatch = /^\d{3}-\d{3}-\d{4}$/,
emailMatch = /^\[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[A-Z]{2,4}$/;
var errors = [];
if (phone){
event.preventDefault();
errors.push("The Phone Number is required.");
return false;
} else if (tomatch.test(phone)){
return true;
} else {
event.preventDefault();
errors.push("The phone number must be formated as follows: XXX-XXX-XXXX.");
return false;
}
if (name === null || name === " "){
event.preventDefault();
errors.push("The Name is required.");
return false;
} else {
return true;
}
if (email === null || email === " "){
event.preventDefault();
errors.push("The email is required.");
return false;
} else if (emailMatch.test(email)){
return true;
} else {
event.preventDefault();
errors.push("The email must be formated as follows: name#domain.com.");
return false;
}
if (address === null || address === " "){
event.preventDefault();
errors.push("The Address is required.");
return false;
} else {
return true;
}
if(errors.length > 0){
for(var i=0;i<errors.length;i++){
alert(errors)
}
return false;
} else {
return true;
}
}
html:
Send Us An Email
<form enctype="multipart/form-data" action="assets/mailer.php" method="POST" id="form1" onSubmit="return validateForm()">
<label for="Name">Name:</label><br />
<input size="100%" type="text" name="name" id="name"><br>
<label for="Email">E-mail:</label><br />
<input size="100%" type="text" name="email" id="email" value=""><br />
<label for="Phone">Phone Number:</label><br />
<input size="100%" type="text" name="phonenumber" id="phonenumber" value=""><br />
<label for="Address">Shipping Address:</label><br />
<input size="100%" type="text" name="address" id="address" value=""><br />
<label for="comment">Input Comments/Questions:</label><br />
<input size="100%" type="text" name="comment" value=""><br><br>
Please choose a file: <br />
<input name="uploaded" type="file" /><br />
<br />
<input size="100%" type="submit" value="Submit" /><br />
<input size="100%" type="reset" value="Reset">
</form>
<script type="text/javascript" src="./assets/validation.js">
I don't know where to start from, but if you need your own validation you should remove required attribute from the inputs because FF for example will check the form instead of your validation function.
Executing event.preventDefault(); what do you think you have in event?
Properlly you should pass it when calling the function on submit and supply an argument in the function definition
onSubmit="validateForm(event);"
and function definition should be:
function validateForm(event) {
...
so you can do event.preventDefault()
...
}
You may have other problems too, but at least you will get the validation function executed and you;ll have event in it
COMPLETE EXAMPLE ADDED:
<script>
function validateForm(event) {
var phone = document.getElementById("phonenumber").value,
email = document.getElementById("email").value,
name = document.getElementById("name").value,
address = document.getElementById("address").value,
tomatch = /^\d{3}-\d{3}-\d{4}$/,
emailMatch = /^\[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[A-Z]{2,4}$/,
errors = [];
if (!phone){
errors.push("The Phone Number is required.");
} else if (!tomatch.test(phone)){
errors.push("The phone number must be formated as follows: XXX-XXX-XXXX.");
}
if (!name){
errors.push("The Name is required");
}
if (!email){
errors.push("The email is required.");
} else if (!emailMatch.test(email)){
errors.push("The email must be formated as follows: name#domain.com.");
}
if (!address){
errors.push("The Address is required.");
}
if (errors.length) {
event.preventDefault();
alert(errors.join("\n"));
}
}
</script>
<form enctype="multipart/form-data" action="assets/mailer.php" method="POST" id="form1" onSubmit="validateForm(event)">
<label for="Name">Name:</label><br />
<input size="100%" type="text" name="name" id="name"><br>
<label for="Email">E-mail:</label><br />
<input size="100%" type="text" name="email" id="email" value=""><br />
<label for="Phone">Phone Number:</label><br />
<input size="100%" type="text" name="phonenumber" id="phonenumber" value=""><br />
<label for="Address">Shipping Address:</label><br />
<input size="100%" type="text" name="address" id="address" value=""><br />
<label for="comment">Input Comments/Questions:</label><br />
<input size="100%" type="text" name="comment" value=""><br><br>
Please choose a file: <br />
<input name="uploaded" type="file" /><br />
<br />
<input size="100%" type="submit" value="Submit" /><br />
<input size="100%" type="reset" value="Reset">
</form>
Related
I have form. Form include name,lastname,email,phone etc. If anybody submit the form without filling email adress my database record this email adress in blank. After this situation if this situation repeat, warning message: same email adress. (First email adress =>blank Second email adress => blank) I want to use regex. Users have to fill email adress. But I could not found any examples. Thanks to much.
Please have a look at the related code:
if (userExists.equals("")) {
bindingResult.rejectValue("email", "error.user", "Lütfen email adresinizi giriniz.");
}
if (userExists != null) {
bindingResult.rejectValue("email", "error.user", "Verilen e-postayla kayıtlı bir kullanıcı var");
}
How about some JavaScript validation code perhaps something like this which doesn't let the form actually submit if the Email field is blank:
<script type="text/javascript"> <!--
function jsValidatePg() {
// Dim var.
var strValid;
// Init.
strValid = "";
// Set var.
if (document.frmMain.Email.value == "") {
strValid = "The Email field must be filled in.";
}
// Determine if valid.
if (strValid == "") {
return true;
}
else {
alert(strValid);
return false;
}
}
//-->
</script>
<form id="frmMain" name="frmMain" action="mypage2.asp" method="post">
<input type="text" name="FirstName" size="15" maxlength="25" value="">
<input type="text" name="LastName" size="15" maxlength="25" value="">
<input type="text" name="Email" size="15" maxlength="25" value="">
<input type="text" name="Phone" size="15" maxlength="25" value="">
<input type="submit" name="btnSubmit" value="Submit" onClick="return jsValidatePg();">
i have a simple php email form, but i am getting spam emails. I have added a check input, User have to fill the input. If input value equal to 12 then submit the form, otherwise don't submit the form with a popup error.(Please do the math.)
<form action="" method="post">
<input type="text" name="name" placeholder="name" required>
<input type="text" name="email" placeholder="email" required>
<input type="text" name="phone" placeholder="phone" required>
<div class="check">
<label>6 x 2 =</label>
<input type="text" name="not_robot" required="required">
</div>
<input type="submit" value="submit">
</form>
i am using php method below:
if(isset($_POST['not_robot']) !== 12 && isset($_POST['not_robot']) !== ''){
echo '<script type="text/javascript">alert("Please do the math, if you are human.");</script>';
}else{
//email script here
}
when i submit form, error popup appear saying "Please do the math, if you are human", but after i close the popup, it also send email.
Any help appreaciated Thanks
P.S: if check method is possible using javascript or jquery it would be a great help.
You need to test on the client:
Plain JS
window.onload=function() {
document.querySelector("form").onsubmit=function(e) {
var val = this.elements["not_robot"].value;
return !isNaN(val) && parseInt(Number(val)) == val && !isNaN(parseInt(val, 10);
}
}
jQuery:
$(function() {
$("form").on("submit",function(e) {
var val = $("[name='not_robot'"].val();
if (isNaN(val) || !parseInt(Number(val)) == val || isNaN(parseInt(val, 10)) e.preventDefault();
}
}
Try to check when submitting the form. Go with below code or link-
JSFiddle
HTML Code-
<form action="" method="post">
<input type="text" name="name" placeholder="name" required>
<input type="text" name="email" placeholder="email" required>
<input type="text" name="phone" placeholder="phone" required>
<div class="check">
<label>6 x 2 =</label>
<input type="text" name="not_robot" required="required">
</div>
<input type="submit" value="submit">
</form>
JAVASCRIPT Code-
$('form').submit(function() {
if (parseInt($('input[name="not_robot"]').val()) == 12) {
return true;
}
else{
alert('You not enterd the correct value');
return false;
}
});
Don't try to prevent sending spam mail this way. My suggestion is to apply csrf protection and also google captcha. You can use this library for csrf protection. And for google captcha use this
If you want to validate through PHP..Below is the way
if(is_numeric($_POST['not_robot']) && !empty($_POST['not_robot'])){
echo '<script type="text/javascript">alert("Please do the math, if you are human.");</script>';
}else{
//email script here
}
Ways :
Use PHP exit() function to exits the current script execution.we can use this function with (or without) an message.
Syntax : exit(message) OR exit()
We can also use return;
Here, the control will return to the script that invoked the running of that file.
Try this :
if(isset(($_POST['not_robot']) != '12') && (isset($_POST['not_robot']) !== '')){
/* alert here */
exit();
}else{
//email script here
}
HTML:
<form action="" method="post" name="form1">
<input type="text" name="name" placeholder="name" required>
<input type="text" name="email" placeholder="email" required>
<input type="text" name="phone" placeholder="phone" required>
<div class="check">
<label>6 x 2 =</label>
<input type="text" name="not_robot" id="not_robot" required="required" />
</div>
<input type="button" value="submit" onClick="checkForm()">
</form>
JavaScipt:
function checkForm()
{
if(document.getElementById('not_robot').value == "12" && document.getElementById('not_robot').value != "")
{
alert('ok');
document.forms['form1'].submit();
}else{
alert('not ok');
}
}
Im trying to build a HTML form which will validate if a user is entering all the values in each of the input boxes. So far I've found in google examples that when the user leaves the input box blank it would call alert() which is annoying for users if they have to fill up about 10 boxes and then by accident they hit submit now they have to close 10 alerts. I was thinking if is possible to just show a red message next to the empty box(es) indicating which boxes are empty.
Here is my code showing alerts:
<form name="ExamEntry" method="POST">
<input type="text" id="name" name="name" />
<input type="text" id="subject" name="subject" />
<input type="text" id="examnumber" name="examNumber" />
<input type="submit" name="submit" value="Submit" onlick="return validateForm()" />
</form>
javascript:
function validateForm(){
var result = true;
var msg = "";
if(document.ExamEntry.name.value==""){
msg+="You must enter your Name \n";
document.ExamEntry.name.focus();
document.getElementById('name').style.color="red";
result = false;
}
if(document.ExamEntry.subject.value==""){
msg+="You must enter the Subject \n";
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color="red";
result = false;
}
if(document.ExamEntry.examNumber.value=="")
{
msg+="You must enter the Examination Number \n";
document.ExamEntry.examNumber.focus;
document.getElementById('examnumber').style.color="red";
result = false;
}
if(document.ExamEntry.examNumber.value.length!=4)
{
msg+="Your Examination Number must be 4 characters long \n";
document.ExamEntry.examNumber.focus;
document.getElementById('examnumber').style.color="red";
result = false;
}
var lvlmsg="";
for(var i=0; i < document.ExamEntry.level.length; i++)
{
if(document.ExamEntry.level[i].checked)
{
lvlmsg = document.ExamEntry.level[i].value;
break;
}
}
if(lvlmsg=="")
{
msg+="You Must Indicate Your Level";
result=false;
document.getElementById('radioButtons').style.color="red";
}
else
{
alert(lvlmsg);
}
if(msg==""){
return result;
}
else{
alert(msg);
return result;
}
}
Any ideas?
Create a span element after each input:
<form name="ExamEntry" method="POST">
<input type="text" id="name" name="name" /><span id="name-msg"></span>
<input type="text" id="subject" name="subject" /> <span id="subject-msg"></span>
<input type="text" id="examnumber" name="examNumber" /> <span id="examnumber-msg"></span>
<input type="submit" name="submit" value="Submit" onlick="return validateForm()" />
</form>
Then instead of doing this:
msg+="You Must Indicate Your Level";
Do:
var msg = document.createTextNode("You Must Indicate Your Level");
document.getElementById('name-msg').appendChild(msg);
And don't forget to remove alerts!
Make sure in your actual code that you are using onclick and not onlick ;)
When I am building form validations, I create a hidden inline span next to each element.
<form name="ExamEntry" method="POST">
<input type="text" id="name" name="name" /><span>Please use a valid name.</span>
<input type="text" id="subject" name="subject" /><span>Please use a valid subject.</span>
<input type="text" id="examnumber" name="examNumber" /><span>Please use a valid exam number.</span>
<input type="submit" name="submit" value="Submit" onlick="return validateForm()" />
</form>
Then in your css, do something like:
input + span {
display:none;
color: red;
}
In your js remove the alerts, and add something like this for each input:
document.getElementById("[id]").style.display = "inline";
Im learning Javascript and am trying to set up a basic form validation which should have the following functionality:
If error is found change text field background color to red, change field value to error message
If no errors are found, proceed
My problem
The validation is working BUT even if no errors is found it still displays an error message...what am I doing wrong?
Code follows:
function validate(){
//form validation
var name=document.getElementById("name");
var surname=document.getElementById('surname');
//name
if (name.value=='') {
name.style.backgroundColor="red";
name.style.color="white";
name.value="Name is required"
return false;
}
else if(isNaN(name)==true){
name.style.backgroundColor="red";
name.style.color="white";
name.value="Name: Only enter letters A-Z"
return false;
}
//surname
if (surname.value == ""){
surname.style.backgroundColor="red";
surname.style.color="white";
surname.value="Surname is required"
return false;
}
else if(isNaN(name)==true){
surname.style.backgroundColor="red";
surname.style.color="white";
surname.value="Surname: Only enter letters A-Z"
return false;
}
return true;
}
HTML
<form id="enquire" method="post">
<h2>Test Drive an Audi Today</h2>
<input type="text" id="name" value="Name" class="textbox" name="name" onfocus="if(this.value=='Name' || this.value=='Name is required' || this.value=='Name: Only enter letters A-Z' ) this.value='';" /><br />
<br />
<input type="text" id="surname" value="Surname" class="textbox" name="surname" onfocus="if(this.value=='Surname') this.value='';" /><br />
<input type="submit" name="submit" class="butt" value="Send" onclick="return validate()" />
You need to pass the value of the input fields to isNaN() like, now you are passing the dom element which will always return true since it is not a number
isNaN(name.value)
Demo: Fiddle
You should use onsubmit event of form instead of click.
<form id="enquire" method="post" onsubmit="return validate()">
I am trying to build a website with a webform. I am using Godaddy's default webform PHP and I am not sure how to validate the form for required fields.
I want the user to not be able to submit the form prior to validation. I found JavaScript files online submitted by other users that address this problem but I can not seem to get it to work.
<script language="javascript" type="text/javascript">
function checkForm() {
if (form.FirstName.value == "") {
alert("Please enter your first name");
form.FirstName.focus();
return false;
}
if (form.LastName.value == "") {
alert("Please enter your last name");
form.LastName.focus();
return false;
}
var email = form.email.value;
if (email.indexOf('#') == -1) {
alert("Plelase enter valid email");
form.email.focus();
return false;
}
return true;
}
</script>
Below is the form:
<form onsubmit="return checkForm()" action="/webformmailer.php" method="post">
<input type="hidden" name="subject" value="Submission" />
<input type="hidden" name="redirect" value="thankyou.html" />
<span>First Name:</span><br>
<input type="text" name="FirstName"/><br>
<span>Last Name:</span><br>
<input type="text" name="LastName" /><br>
<span>*Email:</span><br>
<input type="text" name="email" /><br>
<span>*Comments:</span><br>
<textarea name="comments" cols="40" rows="10">
</textarea><br>
<input type="submit" name="submit" value="submit"/> <span id ="required">*required field</span>
<input type="hidden" name="form_order" value="alpha"/> <input type="hidden" name="form_delivery" value="daily"/> <input type="hidden" name="form_format" value="html"/>
I tried submitting without entering anything and it redirects me to the thank you.
form is not defined in the function. There are several ways to handle this. The simplest would be to change return checkForm() to return checkForm(this) and
function checkForm(form) {
In the form, change checkForm() to checkForm(this). Then, in your javascript, change function checkForm() { to function checkForm(form) {
Maybe this will help.
You forgot 2 thing:
first, please add name="form" into
<form name="form" onsubmit="return checkForm()" action="/webformmailer.php" method="post">
second, you misstake close form, please add this code to end of HTML
</form>
Your HTML will look like:
<form name="form" onsubmit="return checkForm()" action="/webformmailer.php" method="post">
<input type="hidden" name="subject" value="Submission" />
<input type="hidden" name="redirect" value="thankyou.html" />
<span>First Name:</span><br>
<input type="text" name="FirstName"/><br>
<span>Last Name:</span><br>
<input type="text" name="LastName" /><br>
<span>*Email:</span><br>
<input type="text" name="email" /><br>
<span>*Comments:</span><br>
<textarea name="comments" cols="40" rows="10"></textarea><br>
<input type="submit" name="submit" value="submit"/>
<span id ="required">*required field</span>
<input type="hidden" name="form_order" value="alpha"/>
<input type="hidden" name="form_delivery" value="daily"/>
<input type="hidden" name="form_format" value="html"/>
</form>
1 other thing is in javascript, function to check email address is incorrect, Correct is:
var email = form.email.value;
var re = /^[\w-]+(\.[\w-]+)*#([\w-]+\.)+[a-zA-Z]{2,7}$/;
if (!email.match(re) || !email) {
// incorrect email address
}
New script will be:
<script language="javascript" type="text/javascript">
function checkForm() {
if (form.FirstName.value == "") {
alert("Please enter your first name");
form.FirstName.focus();
return false;
}
if (form.LastName.value == "") {
alert("Please enter your last name");
form.LastName.focus();
return false;
}
var email = form.email.value;
var re = /^[\w-]+(\.[\w-]+)*#([\w-]+\.)+[a-zA-Z]{2,7}$/;
if (!email.match(re) || !email) {
alert("Plelase enter valid email");
form.email.focus();
return false;
}
return true;
}
</script>
Goodluck!