I am using a subscribe news letter script by using MySQL and PHP. When the user enters the e-mail and clicks the button the e-mail is added to database.
The issue is that while clicking the button without entering an e-mail, the data base is updating with an empty record. How can I stop submitting the empty fields and force the user to enter an e-mail?
Here is my HTML:
<form id="myForm" action="update.php" method="post">
<input type="hidden" name="action" value="update" />
<input type="text" name="email" id="email" value="Enter your email here" onfocus="if (this.value == 'Enter your email here') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Enter your email here';}" onwebkitspeechchange="this.value = this.value.replace('Enter your email here','')"; style=" color:#999; font-size:1em;width:200px; font-style:italic; font-family:"Times New Roman", Times, serif;"/>
<input class="button" type="image" src="rss.png" />
</form>
Sounds to me like you need to do some form validation before you take the user input and insert it into your database. It's dangerous to do as you're doing.
Why not use one of the many plugins out there:
http://www.queness.com/post/10104/powerful-javascript-form-validation-plugins
This is a useful tutorial on using the jquery validation plugin: http://docs.jquery.com/Plugins/Validation
Ignore the styling in their example and focus on the core aspects. In your case, the most useful line is:
<input id="cemail" name="email" size="25" class="required email" />
Roughly, you would need to do something like..
var form = $('#mtForm');
$('input').change(function(){
if($((this).val() == ''){
form.unbind('submit').submit(function(){
return false;
});
}
else{
form.unbind('submit');
}
})
You should change the value attribute of your email field to a placeholder attribute. The onfocus, onwebkitspeechchange and onblur code can be removed from the email input tag.
You can use something like this to check for a blank field if that's the only type of validation you're after (below is written with jQuery).
$(function(){
$('#myForm').submit(function(e){
if ($('#email').val().trim() == "") {
// some sort of notification here
e.preventDefault();
return false;
}
});
});
Ideally, you would validate the form on the client side (javascript/JQuery) as well as the server side (php).
For clarity I will remove the inline code on your input box to get this:
<input type="text" name="email" id="email" value="Enter your email here" />
Note - You may use
placeholder='Enter your email here'
to get the prompt in your input box.
Client side validation using HTML5
Make a required field with email format validation:
<input type="email" name="email" id="email" value="Enter your email here" required="required"/>
Client side validation using javascript/JQuery - example.js
JQuery:
$('#email').bind('blur', function() {
if (!validateEmail($(this).val()) {
// Add errors to form or other logic such as disable submit
}
});
function validateEmail($email) {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
return emailReg.test($email);
}
}
Server side validation - update.php
// Require the email
if (empty($_POST['email'])) {
$error_message = 'You must enter an email!';
} else if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$error_message = 'Invalid email format. Example: example#example.example';
} else { // If no errors, continue processing the form
// process the form, enter email
}
The HTML5 alone will prevent submission of the form, however only more recent browsers support HTML5.
Hope this is helpful!
Related
I'm making two forms with html and javascript, one for "log in" and one for "register". Im using javascript to check that the inputs on the forms are valid. Im running into an issue where the "email" field on the "log in" form is being validated properly, but the "email" field on my "register" form is not, although they are using nearly identical event listeners to validate the inputs.
this is a condensed version of the code that I am using to do this
<html>
<form class="forms" id="login-form" onsubmit="return false" novalidate>
<h1>Log In</h1>
<div class="form-div">
<label for="email">Your Email:</label>
<input type="email" id="email" name="email" required>
<span class="error"></span>
</div>
<button class="wide-buttons" type="submit">Log In</button>
<p onclick="toggleForms()">Need an account? Click here to sign up!</p>
</form>
<form class="forms" id="register-form" onsubmit="return false" novalidate>
<h1>Register</h1>
<div class="form-div">
<label for="email">Your Email:</label>
<input type="email" id="register-email" name="register-email" required>
<span class="error"></span>
</div>
<button class="wide-buttons" type="submit" onclick="validateRegister()">Sign Up</button>
<p onclick="toggleForms()">Already have an account? Click here to log in!</p>
</form>
<script>
const loginForm = document.getElementById("login-form");
const emailError = document.querySelector("#email + span.error");
const registerForm = document.getElementById('register-form');
const regEmailError = document.querySelector("#register-email + span.error");
loginForm.addEventListener("submit", (event) => {
if (!email.validity.valid) {
emailError.textContent = "You must enter a valid email address";
}
});
registerForm.addEventListener("submit", (event) => {
if (!email.validity.valid) {
regEmailError.textContent = "You must enter a valid email address";
}
});
</script>
Im using event listeners for a "submit" event on each form and the one for "loginForm" Is working the way that I intend it to, but the one for "registerForm" is showing my error message when the email is a valid email or anything else is put into the email field. Im stumped by this considering the listeners are practically identical. I don't need to actually submit the form to anything, I'm just trying to learn how some basic form validation works. This code is a snippet of everything else that I have written, but my passwords, checkboxes, etc. are working fine for me. I just need to know how to get the "registerForm" event listener to work the same way that the "loginForm" one is.
edit: Im aware of the onclick="validateRegister()" on the register form- I have removed this in my code and I am still having the issue.
Any help, constructive criticism, or funny jokes are appreciated.
thanks.
It looks like you are trying to check the validity of the email input element on both forms, but you should be checking the validity of the register-email input element on the registerForm event listener.
Change:
if (!email.validity.valid) {
regEmailError.textContent = "You must enter a valid email address";
}
To:
const registerEmail = document.getElementById('register-email');
if (!registerEmail.validity.valid) {
regEmailError.textContent = "You must enter a valid email address";
}
and it should be ok
Edit1: Ofc you can declare registerEmail above event listener
I'm trying to make validate if an email form field is not empty, of course I'm learning by making mistakes, but some explanation is needed from any of You Pro guys.
Heres wat I have and it's not working, all do it looks logical to me.
<script>
document.getElementById('regform').addEventListener("submit", function(e))
{
if(document.querySelector("#mail")=='')
{
e.alert("You need to provide a valid email");
}
});
</script>
I'm kind of confused here.
This is the HTML:
<form class="login_form" id="regform" action="" method="post">
<input type="email" name="mail" id="mail" placeholder="Your # email" required>
<input type="submit" value="INGRESAR">
</form>
<script>
document.getElementById('regform').addEventListener("submit", function(e))
{
if(document.querySelector("#mail").value == '')
{
e.alert("You need to provide a valid email");
}
}
</script>
get value from input text using document.querySelector("#mail").value anddocument.querySelector("#mail") only get element
I have a form with an option element on top and an email field.
<form class="form-versenden" action="mainVersendet.php" method="post" name="send">
<div class="form-group">
<h4>Bitte tragen Sie die folgenden Daten ein</h4>
<div class="form-group">
<label for="versandart">Versandart</label>
<select class="form-control" id="versandart" name="versandart" autofocus>
<option value="both">E-Mail und Druck</option>
<option value="onlyEmail">Nur E-Mail</option>
<option value="onlyPrint">Nur Druck</option>
</select>
</div>
<div class="form-group">
<label for="email">E-Mail</label>
<input type="email" class="form-control" id="email" placeholder="email" name="email">
</div>
<button class="btn" type="submit">Versenden</button>
</div>
</form>
Depending on what the user chooses, I have to check if an email address is entered in the case 'both' and 'onlyEmail'. Because email is not required in all 3 cases I can't use the required element of HTML for the email field. So I tried to test it on the submit event like this:
document.querySelector('form[name="send"]').addEventListener("submit", validateFields);
function validateFields(){
var versandart = document.getElementById("versandart");
var email = document.getElementById("email");
if (versandart.value == 'both' || versandart.value == 'onlyEmail'){
if(email.value == ''){
email.setCustomValidity('EMail muss eingegeben werden');
return false;
}else if(CHECK HERE if Mail is not correct){
email.setCustomValidity('EMail format is not correct');
return false;
}else{
//in this case email is not empthy and is correct
return true;
}
}
}
But this is not working because I overwrite the standard HTML check for a valid email address. So I have to check it again at the point 'CHECK HERE if Mail is not correct'.
How can I do that and is that the right way? Or should I add an onchangelistener to the versandart field and add the required tag to the email field if the selected value is fitting into the first two cases?
In your else if, use the isEmail() function like this:
else if(email.value.isEmail()) {
return true;
// Now the form will get submitted to the PHP script.
}
string.isEmail() returns true if the entered pattern matches an email address, otherwise false.
Please don't forget to do server side form validation, too, though. If a cracker switches JavaScript off, they may cause mayhem in your system if you only have JavaScript validation -- especially as you apparently can't use required HTML attribute for your email input.
This not working with Jquery Latest version of CDN (Content Delivery Network):
Validating HTML forms is a very important aspect during form submission. jQuery helps in validating forms at client side. The following steps are required to validate a form.
Step 1: Create a Simple HTML Form
To create the form use the following code.
<h1>Fill out your information</h1>
<form id="regForm" method="post">
<input type="text" name="fullname" id="fullname" placeholder="Your Full Name"/>
<input type="text" name="email" id="email" placeholder="Email ID"/>
<input type="text" name="mobileno" id="mobileno" id="mobileno" placeholder="Mobile Number" maxlength="10"/>
<input type="text" name="address" id="address" placeholder="Address"/>
<input type="password" name="password" id="password" value="" placeholder="Password"/>
<input type="password" name="repassword" id="repassword" value="" placeholder="RetypePassword"/>
<button name="submit" type="button" id="btnvalidate">Click to Submit</button>
</form>
This is the form view of the above code
Step 2: Include the Latest jQuery Library
The latest jquery library can be downloaded from https://jquery.com/. Add the latest library to the head section of HTML page.
Step 3: Add a Function to Validate Form
Add the jquery function within the "" tags in the HTML form. Use the following code to validate the form.
<script type="text/javascript">
//Find the values added in form using the id of each fields. The ".val()" function finds the value added in the form fields.
var fullname = $('#fullname').val();
var address = $('#address').val();
var mobileno = $('#mobileno').val();
var email = $('#email').val();
var indexat = email.indexOf("#"); //Index of "#" in the email field
var indexdot = email.indexOf("."); //Index of "." in the email field
var password = $('#password').val();
var repassword = $('#repassword').val();
//Function will execute when the button "Click to Submit" is clicked.
$('#btnvalidate').click(function() {
//Blank field validation of fullname, mobile no and address. The function will generate an alert message if "fullname" or "mobile no" or "address" field is blank
if(fullname == '')
{
alert('Please enter your Full Name');
$('#fullname').focus(); //The focus function will move the cursor to "fullname" field
}
else if(address == '')
{
alert('Please enter your Address');
$('#address').focus();
}
else if(mobileno == '')
{
alert('Please enter your Mobile Number');
$('#address').focus();
}
//Validation of valid email address. The function will generate an alert message if "email" field is blank or incorrect
else if(indexat < 1 || (indexdot-indexat) < 2)
{
alert('Please enter a valid Email Id');
$('#email').focus();
}
//Validation of password. The function will generate an alert message if "password" field is not same as "retype password".
else if(password == '' && password != repassword)
{
alert('Password and Retype password donot match');
$('#repassword').focus();
}
});
</script>
you have to get all the text field values inside your click event.
I have the following script which if the users has the browser ie9 then we fix the known issue regarding ie9 not supporting place holders:
if (isIE9) { // ie9
// this is html5 placeholder fix for inputs, inputs with placeholder-no-fix class will be skipped(e.g: we need this for password fields)
jQuery('input[placeholder]:not(.placeholder-no-fix), textarea[placeholder]:not(.placeholder-no-fix)').each(function() {
var input = jQuery(this);
if (input.val() == '' && input.attr("placeholder") != '') {
input.addClass("placeholder").val(input.attr('placeholder'));
}
input.focus(function() {
if (input.val() == input.attr('placeholder')) {
input.val('');
}
});
input.blur(function() {
if (input.val() == '' || input.val() == input.attr('placeholder')) {
input.val(input.attr('placeholder'));
}
});
});
}
When I load the page in ie9 I see the place holder for the email box, but the password box has decided to take the placeholder and make it look like someone has entered a value as shown here:
My markup is as follows:
<div class="form-group">
<input id="EmailAddress" class="form-control" type="text" value="" placeholder="Please enter your email address" name="EmailAddress" data-val-required="Email Address is required" data-val="true" autocomplete="off" maxlength="320">
</div>
<div class="form-group">
<input id="Password" class="form-control" type="Password" value="" placeholder="Password" name="Password" data-val-required="Password is required" data-val="true" autocomplete="off" maxlength="50">
</div>
Can anyone suggest anything that might help me cure the problem?
I also added placeholder-no-fix to the password class but yet when viewed in ie9 the password field is empty it does not show the place holder.
You're setting the value (.val()) of the password field to the string "Password", which it treats as a password and hides the characters.
I suppose as a dirty-ish hack you could set the input type to text until they focus the field, then set it to password until the field is empty on blur again (it'd obviously be bad to set it to text if their password was in there!).
I recommend you using an extra position: absolute; div as the placeholder fallback for IE 9. Simply show / hide the div onblur.
Using value as placeholder would require the user to delete everything before filling in the fields, and it would definitely have the ****** issue in the password field.