I am trying to create a form that checks for JavaScript validation before it goes into my database basically if a user does not type in anything then a alert will come up, however when viewing it in the browser, when I don't place any text inside any of the text boxes and hit submit, no alert comes up, no nothing i'd appreciate it if you could help me out please
HTML
<body>
<form action="update.php?eventID=<?=$contact['eventID']?>" name="myForm" onsubmit="return validate()" method="post">
<label for="eventTitle">Event Title</label>
<input type="text" name="eventTitle" value="?=$contact['eventTitle']?>" id="eventTitle">
<label for="eventDescription">Event Description</label>
<input type="text" name="eventDescription" value="<?=$contact['eventDescription']?>" id="eventDescription">
<label for="eventStartDate">Event Start Date</label>
<input type="text" name="eventStartDate" value="<?=$contact['eventStartDate']?>" id="eventStartDate">
<label for="eventEndDate">Event End Date</label>
<input type="text" name="eventEndDate" value="<?=$contact['eventEndDate']?>" id="eventEndDate">
<label for="eventPrice">Event Price</label>
<input type="text" name="eventPrice" value="<?=$contact['eventPrice']?>" id="eventPrice">
<input type="submit" value="Update">
</form>
<script src="update.js"></script>
</body>
JavaScript
function validate() {
if( document.myForm.eventTitle.value == "" ) {
alert( "Please enter a Event Title" );
document.myForm.eventTitle.focus() ;
return false;
}
if( document.myForm.eventDescription.value == "" ) {
alert( "Please enter a event Description!" );
document.myForm.eventDescription.focus() ;
return false;
}
if( document.myForm.eventStartDate.value == "" ) {
alert( "Please enter a event Start Date!" );
document.myForm.eventStartDate.focus() ;
return false;
}
if( document.myForm.eventEndDate.value == "" ) {
alert( "Please enter a event End Date!" );
document.myForm.eventEndDate.focus() ;
return false;
}
if( document.myForm.eventPrice.value == "" ) {
alert( "Please enter a event End Date!" );
document.myForm.eventPrice.focus() ;
return false;
}
return( true );
}
The only error I found in your code is a missing minor sign before question mark in the line where you define eventTitle
Fix the typo, try clearing browser cache, and try pressing F12 to access debug information to better understand what's going wrong.
You have given value for each input e.g. value="?=$contact['eventTitle']?>"
If you remove that you will get an alert.
Related
The phone number and the email must be valid.
This is a basic popup contact form without the phone number validation. I would like to validate the phone number. I heard about regex but i´m not sure how to implement in the code.
Since i don´t understand javascrip yet i hope you can help me.
<form action="#" method="post" id="form">
<h2>Contact Us</h2><hr/>
<input type="text" name="company" id="company" placeholder="Company"/>
<input type="text" name="name" id="name" placeholder="Name"/>
<input type="text" name="email" id="email" placeholder="Email"/>
<input type="text" name="phone" id="email" placeholder="Phone"/>
<a id="submit" href="javascript: check_empty()">Send</a>
</form>
function check_empty(){
if(document.getElementById('company').value == ""
|| document.getElementById('name').value == ""
||document.getElementById('email').value == ""
||document.getElementById('phone').value == "" ){
alert ("Please, fill the fields!");
}
else {
document.getElementById('form').submit();
}
}
//function to display Popup
function div_show(){
document.getElementById('abc').style.display = "block";
}
//function to check target element
function check(e){
var target = (e && e.target) || (event && event.srcElement);
var obj = document.getElementById('abc');
var obj2 = document.getElementById('popup');
checkParent(target)?obj.style.display='none':null;
target==obj2?obj.style.display='block':null;
}
//function to check parent node and return result accordingly
function checkParent(t){
while(t.parentNode){
if(t==document.getElementById('abc'))
{
return false
}
else if(t==document.getElementById('close'))
{
return true
}
t=t.parentNode
}
return true
}
I am adding a data validation to my code. I want to make sure the event title is not blank, and the zip code entered is valid. The javascript does not work. Can you tell me why?
<form name="form1" action="organize.php" onSubmit="return validateform1();" method="post" enctype="multipart/form-data">
<div class="form-element">
<label for="event_title">Event Title</label>
<input type="text" name="event_title" id="dob" />
</div>
<div class="form-element">
<label for="zip">Zip Code</label>
<input type="text" name="zip" id="dob" />
</div>
<script language="javascript">
function validateform1(){
var zipcode = /^\+?([0-9]{2})\)?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/;
if(document.form1.event_title.value==""){
alert("Enter a title");
return false;
}
else if((!document.form1.zip.value.match(zipcode)){
alert("wrong zip format");
return false;
}
</script>
</form>
you have missed closing ) in this line:
else if((!document.form1.zip.value.match(zipcode)) {
should be :
else if((!document.form1.zip.value.match(zipcode))) {
or:
else if(!document.form1.zip.value.match(zipcode)) {
Always you should see browser console.you can see hint to get rid of your issues.
Probably doesn't help that your ZIP field has id="dob", but I think the main issue is that your function is missing a closing }, and your else if (( has an extra (. Try this:
function validateform1() {
var zipcode = /^\+?([0-9]{2})\)?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/;
if (document.form1.event_title.value == "") {
alert("Enter a title");
return false;
} else if (!document.form1.zip.value.match(zipcode)) {
alert("wrong zip format");
return false;
}
}
Here is the Demo
I am working in Javascript Validation. I want to give Separate colour for the text
" Please enter Valid Email ID "
When User Enter a wrong email id and press, there is one Error message will come. I want give red colour for this Error message. Only for this Error message i need red colour
HTML
<label id="message">We don't Spam. Promise</label> <br />
<input autocomplete="on" type="text" name="booking_email" onkeyup="validate()" id="SignupText" class="InputSignup" placeholder="Enter Your Email" />
<input type="submit" value="submit" class="subButton" onclick="submitEmail();"/>
JAVASCRIPT
function validate()
{
var booking_email = $('input[name=booking_email]').val();
if(booking_email == '' ){
document.getElementById("message").innerHTML="We don't Spam. Promise";
}else if( /(.+)#(.+){1,}\.(.+){2,}/.test(booking_email) )
{
document.getElementById("message").innerHTML="Your email is valid"
if(event.which == 13){
submitEmail();
}
} else {
document.getElementById("message").innerHTML="Type your email id";
if(event.which == 13){
submitEmail();
}
}
}
function submitEmail()
{
var booking_email = $('input[name=booking_email]').val();
if(booking_email=="")
{
document.getElementById("message").innerHTML="Please enter Your Email ID"
}
else if( /(.+)#(.+){1,}\.(.+){2,}/.test(booking_email) )
{
alert('success');
}
else {document.getElementById("message").innerHTML="Please enter Valid Email ID";}
}
just change
document.getElementById("message").innerHTML="Please enter Your Email ID"
to
document.getElementById("message").innerHTML = "<span style='color:red'>Please enter Your Email ID</span>";
wrapping the text with a span that has the color set to red ?
I created a JSFiddle
I wrapped a <span class='red'></span> around the text and then created a class .red in the css.
Javascript:
document.getElementById("message").innerHTML = "<span class='red'>Please enter Your Email ID</span>";
CSS
.red{
color:red;
}
Whenever you print an error message you could wrap it in a div with a class or error-message
document.getElementById("message").innerHTML="<div class='error-message'>Please enter Valid Email ID</div>";
Then in your CSS file you can do
.error-message
{
color: red;
}
I would recommend:
css:
.error {
color: red;
}
and:
document.getElementById("message").innerHTML = "<span class='error'>Please enter Your Email ID</span>";
Other option would be to keep separate div for your errors and change its visibility and or text accordingly.
However, ultimate solution would be just to use correct input type.
<input type="email" name="email">
it works best as cross-device and it has error handling build in using regexp, so you can get away using those nasty javascript codes :) read more:
http://html5doctor.com/html5-forms-input-types/
friend try this code.. i have used jquery css method which makes solution very easier.you don't need to create class and div for message.You just need to follow below code. I have used jquery css method and I have used it only in success message,but you can use it for all.Just follow the syntax.
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
function validate()
{
var booking_email = $('input[name=booking_email]').val();
if(booking_email == '' ){
document.getElementById("message").innerHTML="We don't Spam. Promise";
}else if( /(.+)#(.+){1,}\.(.+){2,}/.test(booking_email) )
{
document.getElementById("message").innerHTML="Your email is valid"
$('#message').css("color","red");
$('#message').css("font-weight","bold");
if(event.which == 13){
submitEmail();
}
} else {
document.getElementById("message").innerHTML="Type your email id";
if(event.which == 13){
submitEmail();
}
}
}
function submitEmail()
{
var booking_email = $('input[name=booking_email]').val();
if(booking_email=="")
{
document.getElementById("message").innerHTML="Please enter Your Email ID"
}
else if( /(.+)#(.+){1,}\.(.+){2,}/.test(booking_email) )
{
alert('success');
}
else {document.getElementById("message").innerHTML="Please enter Valid Email ID";}
}
</script>
</head>
<body>
<label id="message">We don't Spam. Promise</label> <br />
<input autocomplete="on" type="text" name="booking_email" onkeyup="validate()" id="SignupText" class="InputSignup" placeholder="Enter Your Email" />
<input type="submit" value="submit" class="subButton" onclick="submitEmail();"/>
</body>
</html>
here is demo
http://jsfiddle.net/JHHTw/3/
I have a form that I'm trying to validate, but the email, select country fields seems that are not being validated. Can some one tell me what is the problem?
Here is my javascript:
<script type="text/javascript">
function validateEmail()
{
var emailID = document.form1.EMail.value;
atpos = emailID.indexOf("#");
dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || ( dotpos - atpos < 2 ))
{
alert("Please enter correct email ID")
document.form1.EMail.focus() ;
return false;
}
return( true );
}
function validate()
{
//username password First_n Last_n Company Mobile Email Residence
if( document.form1.First_n.value == "" )
{
alert( "Please enter your first name!" );
document.form1.First_n.focus() ;
return false;
}
if( document.form1.Last_n.value == "" )
{
alert( "Please enter your last name!" );
document.form1.Last_n.focus() ;
return false;
}
if( document.form1.username.value == "" )
{
alert( "Please enter your username!" );
document.form1.username.focus() ;
return false;
}
if( document.form1.password.value == "" )
{
alert( "Please enter your password!" );
document.form1.password.focus() ;
return false;
}
if( document.form1.Company.value == "" )
{
alert( "Please provide us your company name!" );
document.form1.Company.focus() ;
return false;
}
if( document.form1.Mobile.value == "" )
{
alert( "Please provide us your mobile number!" );
document.form1.Mobile.focus() ;
return false;
}
if( document.form1.Email.value == "" )
{
alert( "Please provide us your Email!" );
document.form1.Email.focus() ;
return false;
}
if( document.form1.Email.value != "" )
{
// Put extra check for data format
var ret = validateEmail();
if( ret == false )
{
return false;
}else
return true;
}
if( document.form1.Zip.value == "" ||
isNaN( document.form1.Zip.value ) ||
document.form1.Zip.value.length != 5 )
{
alert( "Please provide a zip in the format #####." );
document.form1.Zip.focus() ;
return false;
}
if( document.form1.Residence.value == "-1" )
{
alert( "Please provide your country!" );
return false;
}
return( true );
}
</script>
And my form html:
<form name="form1" method="post" action="add_new.php" onsubmit="return(validate());">
<div style="clear:both;padding:0px 10px 0 10px;margin-bottom:20px;">
<h5>Interested in</h5>
<input id="toggle-on" class="toggle toggle-left" name="toggle" value="false" type="radio" checked>
<label for="toggle-on" class="btn">Hosting</label>
<input id="toggle-off" class="toggle toggle-right" name="toggle" value="true" type="radio"
><label for="toggle-off" class="btn">Email accounts</label>
</div>
<div style="clear-both;">
<input name="First_n" type="text" placeholder="First Name" class="login-text-lbl-pink-no-width" id="First_n">
<input name="Last_n" type="text" placeholder="Last Name" class="login-text-lbl-pink-no-width" id="Last_n">
</div>
<input name="username" type="text" placeholder="Username" class="login-text-lbl-pink-no-width" id="username"><br/>
<input name="password" type="password" placeholder="Password" class="login-text-lbl-pink-no-width" id="password"><br/>
<input name="Company" type="text" placeholder="Company" class="login-text-lbl-pink-odd" id="Company"> <br/>
<input name="Mobile" type="text" placeholder="Mobile Phone" id="login-text-lbl" class="pink-transparent-item" id="Mobile"> <br/>
<input name="Email" type="text" placeholder="Email" class="login-text-lbl-pink-odd" class="pink-transparent-item" id="Email"> <br/>
<select name="Residence" id="Residence" id="login-text-lbl" style="
background-color: rgba(240, 96, 96, 0.62);
border: none;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
height: 30px;
margin: 5px;
font-style: italic;
width: 90%;
padding: 5px;
color: #34584b;
float: none;"
>
<option value="-1" selected>[choose country]</option>
<option value="US">America</option>
<option value="DE">Germany</option>
<option value="IT">Italy</option>
<option value="HK">Hong Kong</option><br/>
<input name="domain" class="pink-transparent-item" type="text" placeholder="Existing domain" id="login-text-lbl" id="domain"> <br/>
<input type="submit" name="Submit" value="Submit" style='font-family: "Neo Sans Light", Verdana, Tahoma;' class="login-button-pink">
</form>
you form has email id as : "Email" while your validation code has EMail (var emailID = document.form1.EMail.value;)? Use correct control id.
And yes of course you can use regex to validate which is even better.
there's a few things wrong here, but let's try and answer your questions specifically -
Email works fine for me in chrome and firefox, though can't speak for safari, IE, seamonkey, etc.
Your validateEmail() method has the input named as EMail - you won't get it. JS is Case-sensitive.
Even after you do validate, you'll never get to anything past Email because of the return true you have after bringing back the value of validateEmail(). you've left validate() at that point.
As for the other things - you should really run your code through JSLint to check it for errors. I see a couple unclosed braces. I say JSLint because it seems you're a relative beginner at JS, so you probably need the more fundamentalist approach that Crockford brings to code, at least for a little while until you get good at it (no offense intended; we all start at the beginning).
It would probably a lot easier to just use regex for email validation. Check out this StackExchange answer for a good example.
Code snippet from the answer:
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\
".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA
-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
Do couple of things :
1) Put alert statements in your "validate()" and "validateEmail()" functions and make sure you're receiving all the values you expect.
2) If you're using IE, try to load your application in either Chrome or FireFox and go through the built-in debuggers setting up breakpoints in your JS functions.
You can actually use the regular expression method form Fuzzley's answer , for the country field part try using this code,
var country= document.form1.Residence.value ;
if(country != "America"|| country != "Germany"||country != "Italy"||country != "Hong Kong") {
alert("Please provide your country!");
return false;
}
I'm having small trouble with javascript validation. I need to validate the select dropdown in my form. I can validate all fields so far but somehow I cannot validate the select dropdown list? Can someone help me validate my form?
Here is my javascript:
<script type="text/javascript">
if( document.form1.Email.value != "" )
{
// Put extra check for data format
var ret = validateEmail(document.form1.Email);
if( ret == false )
{
return false;
}
}
}
function validate()
{
//username password First_n Last_n Company Mobile Email Residence
if( document.form1.First_n.value == "" )
{
alert( "Please enter your first name!" );
document.form1.First_n.focus() ;
return false;
}
if( document.form1.Last_n.value == "" )
{
alert( "Please enter your last name!" );
document.form1.Last_n.focus() ;
return false;
}
if( document.form1.username.value == "" )
{
alert( "Please enter your username!" );
document.form1.username.focus() ;
return false;
}
if( document.form1.password.value == "" )
{
alert( "Please enter your password!" );
document.form1.password.focus() ;
return false;
}
if( document.form1.Mobile.value == "" )
{
alert( "Please provide us your mobile number!" );
document.form1.Mobile.focus() ;
return false;
}
if( document.form1.Email.value == "" )
{
alert( "Please provide us your Email!" );
document.form1.Email.focus() ;
return false;
}
var yourSelect = document.getElementById('Residence');
alert(yourSelect.options[yourSelect.selectedIndex].value)
if(yourSelect.options[yourSelect.selectedIndex].value == '' )
{
alert( "Please provide your country!" );
return false;
}
if( document.form1.Email.value != "" )
{
// Put extra check for data format
var ret = validateEmail(document.form1.Email);
if( ret == false )
{
return false;
}
}
return( true );
}
</script>
And my form:
<form name="form1" method="post" action="add_new.php" onsubmit="return(validate(false));">
<div style="clear:both;padding:0px 10px 0 10px;margin-bottom:40px;">
<h5>Interested in</h5>
<input id="toggle-on" class="toggle toggle-left" name="toggle" value="Hosting" type="radio" checked>
<label for="toggle-on" class="btn">Hosting</label>
<input id="toggle-off" class="toggle toggle-right" name="toggle" value="Email accounts" type="radio"
><label for="toggle-off" class="btn">Email accounts</label>
</div>
<div style="clear-both;">
<input name="First_n" type="text" placeholder="First Name*" class="login-text-lbl-pink-no-width" id="First_n">
<input name="Last_n" type="text" placeholder="Last Name*" class="login-text-lbl-pink-no-width" id="Last_n">
</div>
<input name="username" type="text" placeholder="Username*" class="login-text-lbl-pink-no-width" id="username"><br/>
<input name="password" type="password" placeholder="Password*" class="login-text-lbl-pink-no-width" id="password"><br/>
<input name="Company" type="text" placeholder="Company" class="login-text-lbl-pink-odd" id="Company"> <br/>
<input name="Mobile" type="text" placeholder="Phone Number*" class="pink-transparent-item" id="Mobile"> <br/>
<input name="Email" type="text" placeholder="Email*" class="login-text-lbl-pink-odd" id="Email"> <br/>
<select name="Residence" id="Residence" style="background-color: rgba(240, 96, 96, 0.62);border: none;-webkit-appearance: none;
-moz-appearance: none;appearance: none;height: 40px;font-style: italic;width: 270px;padding: 10px;margin: 5px;color: #552726;border-radius: 5px;border: none;float: left;" class="required">
<option value="zero" selected>Country*</option>
<option value="US">America</option>
<option value="DE">Germany</option>
<option value="IT">Italy</option>
<option value="HK">Hong Kong</option><br/>
<input name="domain" class="login-text-lbl-pink-odd" type="text" style="width:350px;margin-bottom:40px;" placeholder="Existing domain" id="domain"> <br/>
<input type="submit" name="Submit" value="Submit" style='font-family: "Neo Sans Light", Verdana, Tahoma;' class="login-button-pink">
</form>
I believe the problem is in the email validation that happens just before the country validation, because if an email address is entered it returns from the function regardless of whether the email passed validation, so it never gets to the country bit:
if( document.form1.Email.value != "" )
{
// Put extra check for data format
var ret = validateEmail(document.form1.Email);
if( ret == false )
{
return false;
}else
return true; // delete this line, and the else
}
You want to return false if there's a problem, but you don't want to return true until the end of the function.
UPDATE: The code now shown in the updated question doesn't work because:
You deleted the validateEmail() function declaration (replacing it with a copy of the code I said to change at the end of validate() - unless that was just a weird copy/paste error in the question)
You changed the if test on the country to check for an empty string, but didn't update the corresponding value="zero" to be value=""
If you fix those it works as shown here: http://jsfiddle.net/58A7K/
Note also that the code I showed above can be simplified - you don't need the ret variable:
if( document.form1.Email.value != "" ) {
if (!validateEmail(document.form1.Email)) {
return false;
}
}
The problem is with following code:
if( document.form1.Email.value != "" )
{
// Put extra check for data format
var ret = validateEmail(document.form1.Email);
if( ret == false )
{
return false;
}else
return true;
}
In the above code, when user enters a valid email, your are returning TRUE as a result the code for validating country is never executed.
Remove the else part from above code snippet.