I have a function to check if any text is entered in the email field but it is not working.
I am not sure what I am missing.
This is my Form:
<fieldset>
<legend>Contact Information</legend>
<form action="" id="contactInfo" onsubmit="checkform()">First Name:
<input type="text" name="fname" id="fname">
<br />Last Name:
<input type="text" name="lname" id="laname">
<br />Email:
<input type="text" name="email" id="email">
<br />
<button type="submit">Submit</button>
</form>
</fieldset>
This is my function in a seperate .js file
function checkform(form) {
if (document.form.email.value = "") {
alert("Please enter your email address.");
document.form.email.focus();
return false;
}
return true;
}
Here is a demo.
HTML
<fieldset>
<legend>Contact Information</legend>
<form id="contactInfo" onsubmit="checkform()">
First Name: <input type="text" name="fname" id="fname"><br />
Last Name: <input type="text" name="lname" id="laname"><br />
Email: <input type="text" name="email" id="email"><br />
<button type="submit">Submit</button>
</form>
</fieldset>
JavaScript
function checkform(form)
{
console.log(form);
if(document.forms[0].email.value == ""){
alert("Please enter your email address.");
document.form.email.focus();
return false;
}
return true;
}
Use this instead:
document.forms[0].email.value
or use form ID to retrieve the value.
function checkform(form) {
if (document.forms[0].email.value == "") {
alert("Please enter your email address.");
document.forms[0].email.focus();
return false;
}
}
fiddle
Pass the form in as the argument this to your checkForm() function. This way you can use the checkForm() function with multiple forms. Like so:
<fieldset>
<legend>Contact Information</legend>
<form action="" id="contactInfo" onsubmit="checkform(this)">First Name:
<input type="text" name="fname" id="fname">
<br />Last Name:
<input type="text" name="lname" id="laname">
<br />Email:
<input type="text" name="email" id="email">
<br />
<button type="submit">Submit</button>
</form>
</fieldset>
Then you can access the form element with out the document. prefix from your validation function like so:
function checkform(form) {
if (form.email.value == "") {
alert("Please enter your email address.");
form.email.focus();
return false;
}
return true;
}
(Also, make sure you check form.email.value == "" not form.email.value = "" which is the assignment operator).
Related
the code below was written to validate simple html form with JavaScript and preventDefault() method means that if the required fields are empty then stop form submission and display error or otherwise submit the form if the required fields are not empty.
The problem comes when I click the submit button the form isn't working.
Can anyone please help me to solve the problem?
let form = document.getElementById("signUp");
let uname = document.forms["myForm"]["userName"].value;
let uemail = document.forms["myForm"]["userEmail"].value;
function validateForm() {
if (uname == " ") {
alert("Name is Empty");
} else if (uemail == " ") {
alert("Email is Empty");
return false;
}
return true;
}
form.addEventListener("submit", function(e) {
e.preventDefault();
validateForm();
});
<form id="signUp" name="myForm">
Name: <input type="text" name="uname" id="userName">
<br> Email: <input type="email" name="email" id="userEmail">
<button type="submit">sign up</button>
</form>
With e.preventDefault() you say that the form should not be submitted.
So you only want to call if in case the validation returns false.
Besides that, your uname and uemail is set before the form is submitted. So it won't contain the state of the input fields at the time the form is submitted. You have to move them into your validateForm function.
let form = document.getElementById("signUp");
function validateForm() {
let uname = document.forms["myForm"]["userName"].value;
let uemail = document.forms["myForm"]["userEmail"].value;
if (uname == " ") {
alert("Name is Empty");
} else if (uemail == " ") {
alert("Email is Empty");
return false;
}
return true;
}
form.addEventListener("submit", function(e) {
if (!validateForm()) {
e.preventDefault();
}
});
<form id="signUp" name="myForm">
Name: <input type="text" name="uname" id="userName">
<br> Email: <input type="email" name="email" id="userEmail">
<button type="submit">sign up</button>
</form>
And uname == " " does not test if the name is empty. It tests if it consists of one character that is a space. The same is for uemail == " ". You probably looking for uname.trim() == ""
As you need to verify the data on the server anyways. And in some way need to display an error if the validation fails on the server side.
It is often sufficient to rely on the HTML solutions to verify the form data (if the browser support is decent enough even if it is not complete).
Something like this:
.error {
display: none;
}
input:not(:placeholder-shown):invalid +.error {
display: block;
}
<form id="signUp" name="myForm">
Name: <input type="text" name="uname" id="userName" placeholder="Name" pattern="^(?!^ +$)([\w -&]+)$" required>
<div class="error">Name must not be empty</div>
<br> Email: <input type="email" name="email" id="userEmail" placeholder="Email" required>
<div class="error">Email must be valid</div>
<button type="submit">sign up</button>
</form>
const form = document.getElementById("signUp");
form.addEventListener("submit", (e) => {
e.preventDefault();
if(validate()) {
form.submit()
}
});
const validate = () => {
const name = document.querySelector("#userName");
const email = document.querySelector("#email");
let hasError = false;
if(!(name.value && name.value.length > 4)) {
const nameErr = document.querySelector("#user-name-error");
nameErr.textContent = "Name is required";
hasError = true;
}
if(!(name.value && name.value.length > 0)) {
const emailErr = document.querySelector("#user-email-error");
emailErr.textContent = "Email is required";
hasError = true;
}
return !hasError;
};
<form id="signUp" name="myForm">
<div class="form-group">
<label for="userName">Name: </label>
<input type="text" name="uname" id="userName" />
<p id="user-name-error" style="color: red;"></p>
</div>
<div class="form-group">
<label for="userEmail">Email: </label>
<input type="email" name="email" id="email" />
<p id="user-email-error" style="color: red;"></p>
</div>
<button type="submit">sign up</button>
</form>
<form id="signUp" name="myForm">
<div class="form-group">
<label for="userName">Name: </label>
<input type="text" name="uname" id="userName" required minlength="4"/>
</div>
<div class="form-group">
<label for="userEmail">Email: </label>
<input type="email" name="email" id="email" required pattern="[^#]*#[^.]*\..*"/>
</div>
<button type="submit">sign up</button>
</form>
This is an example using only html, it is only for your use case of course if you want to add more complexe validation use javascript
I'm trying to add validation to the form I made
<fieldset>
<legend>ENTER YOUR INFORMATION HERE FOR DELIVERY</legend>
<form action="" name="deliveryform">
Name* :<input type="text" name="name" id="name">
Phone Number* : <input type="text" name="phonenumber" id="phonenumber">
<span id="warning1"></span>
Address* : <textarea name="address" id="address" required></textarea>
Email* : <input type="text" name="email" id="email">
<span id="warning2"></span>
<input type="submit" id="submitbutton" value="Submit" onsubmit=" return validation()">
</form>
</fieldset>
Javascript
function validation()
{
var name = document.getElementsByName("name").value;
var phonenumber =document.getElementsByName("phonenumber").value;
var email = document.getElementById("email").value;
var emailformat = "[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,}$";
if(name == ""|| null)
{
alert("Please Enter Your Name!");
return false;
}
if(isNaN (phonenumber))
{
document.getElementById("warning1").innerHTML ="Enter numbers only";
return false;
}
if(!email.match(emailformat))
{
document.getElementById("warning2").innerHTML="Please enter the correct format. Example : Abc1234#gmail.com"
return false;
}
else
{
alert("Submitted Successfully")
}
}
Nothing changed except ''Error Loading Page '' message appeared.
Did I miss something?
I thought coding in without and with Jquery in HTML is the same thing..
I want to add Enter key press to Login the system. The JavaScript block has the check function. How to add the Enter key press function? Here is the View code.
#using (Html.BeginForm("Login", "InventoryBarcode", FormMethod.Post, new { id = "main" }))
{
<label for="LoginName" class="uname">Account</label>
<input type="text" name="LoginName" id="LoginName" value="" placeholder="Please Enter Account" />
<label for="LoginPassword" class="youpasswd">Password</label>
<input type="password" name="LoginPassword" id="LoginPassword" value="" placeholder="Please Enter Password" />
<asp:TextBox ID="txtLoginPassword" runat="server" TextMode="Password" placeholder="Please Enter Password"></asp:TextBox>
<span id="message" style="color:red">#ViewBag.Message</span>
<input type="button" name="Login" id="Login" value="login" onclick="Check();" />
}
<script src="~/Scripts/jquery-3.1.1.js"></script>
<script type="text/javascript">
function Check() {
if ($.trim($("#LoginName").val()) === "") {
$("#message").text('Please Enter Account!');
return false;
}
if ($.trim($("#LoginPassword").val()) === "") {
$("#message").text('Please Enter Password!');
return false;
}
$("#Login").hide();
$("#message").text('Login Please Wait...');
$("#main").submit();
}
</script>
I strongly suggest you attach the submit handler:
<input type="submit" name="Login" id="Login" value="login" />
$("#main").on("submit", function(e) {
if ($.trim($("#LoginName").val()) === "") {
$("#message").text('Please Enter Account!');
return false;
}
if ($.trim($("#LoginPassword").val()) === "") {
$("#message").text('Please Enter Password!');
return false;
}
$("#Login").hide();
$("#message").text('Login Please Wait...');
});
I have an HTML form with three mandatory fields in. I don't want the form to submit the AJAX call if they are empty.
$("#contact").submit(function(e){
e.preventDefault();
var ajaxurl = '<?php echo WEB_URL; ?>contact_send.php';
var data = $(this).serializeArray();
console.log(data);
var valid = true;
if( $('input[name="Name"]').val() == '' || $('input[name="Email"]').val() == '' || $('input[name="Phone"]').val() == '') {
valid = false;
}
if(valid) {
$.post(ajaxurl, data, function (response) {
$(".show_homecontact_form_success").fadeIn(1000);
$("#contact")[0].reset();
});
} else {
alert('Please fill in all mandatory fields.');
}
});
<form id="contact" name="contact" method="post" action="">
<label for="Name">Name: *</label>
<input type="text" name="Name" id="name" />
<input name="robotest" type="hidden" value="" />
<label for="Position">Position:</label>
<input type="text" name="Position" id="position" />
<label for="Company">Company:</label>
<input type="text" name="Company" id="company" />
<label for="Address">Address:</label>
<input type="text" name="Address" id="address" />
<label for="Email">Email: *</label>
<input type="text" name="Email" id="email" />
<label for="Email">Phone number: *</label>
<input type="text" name="Phone" id="phone" />
<label for="Event_Subject">What is the subject of the event?:</label>
<input type="text" name="Event_Subject" id="subject" />
<label for="Event_Date">What is the date of the event?:</label>
<input type="text" name="Event_Date" id="date" />
<label for="Additional_info">Additional Information:</label>
<br />
<textarea name="Additional_info" rows="20" cols="20" id="info"></textarea>
<input id="formsubmitted" type="submit" name="submit" value="submit" class="submit-button" />
</form>
This does give the popup box if you try and fill it in empty, but I have received an email with all blank fields.
How is the user getting past the validation and managing to send the form through blank?
More than likely you've not popped in a preventDefault() in there, so the form is doing a normal (non-AJAX) post after your function ends. What's the method/action on your form? Perhaps there doesn't need to be an action at all?
Try this:
$("#contact").submit(function(e){
e.preventDefault();
var ajaxurl = '<?php echo WEB_URL; ?>contact_send.php';
var data = $(this).serializeArray();
console.log(data);
var valid;
if( $('input[name="Name"]').val().length > 0
&& $('input[name="Email"]').val().length > 0
&& $('input[name="Phone"]').val().length > 0) {
valid = true;
} else {
valid = false;
}
if(valid) {
$.post(ajaxurl, data, function (response) {
$(".show_homecontact_form_success").fadeIn(1000);
$("#contact")[0].reset();
});
} else {
alert('Please fill in all mandatory fields.');
}
});
As Jigar pointed out, you can shorten the code by assigning an initial value to the valid variable and removing else block:
var valid = false;
if( $('input[name="Name"]').val().length > 0
&& $('input[name="Email"]').val().length > 0
&& $('input[name="Phone"]').val().length > 0) {
valid = true;
}
I am creating a login/register part to a site. And the login and register forms are on page.
Like:
<form name="loginform" style="text-align:center;" method="post" onsubmit="return validateForm();" action="index.php">
<div class="row">
<input type="text" name="email" id="email" autocomplete="off" placeholder="Email Address" />
</div>
<br />
<div class="row">
<input type="password" name="password" id="password" autocomplete="off" placeholder="Password" />
</div>
<br />
<div class="row">
<button id="submit" type="submit" class="button large arrow-type-2 dark">Log Me In</button>
</div>
</form>
<form name="registerform" style="text-align:center;" method="post" onsubmit="return validatethisForm();" action="index.php">
<div class="row">
<input type="text" name="email" id="email2" autocomplete="off" placeholder="Email Address"/>
</div>
<br />
<div class="row">
<input type="password" name="password" id="password2" autocomplete="off" placeholder="Password"/>
</div>
<br />
<div class="row">
<button id="submit" type="submit" class="button large arrow-type-2 dark">Create Free Account</button>
</div>
</form>
My Js Validation is: ( needs work )
function validateForm()
{
var x=document.forms["loginform"]["email"].value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
var x=document.forms["loginform"]["password"].value;
if (x==null || x=="")
{
alert("Please enter a Password");
return false;
}
}
function validatethisForm()
{
var x=document.forms["registerform"]["email2"].value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
var x=document.forms["registerform"]["password2"].value;
if (x==null || x=="")
{
alert("Please enter a Password");
return false;
}
}
The issue I have is page validation, everything works perfect. But because I have duplicate submit id's , I need to clean this up.
Can you offer suggestions on improving my code above ?
/////////////////////////////////////////
Using: code below for cross browser placeholder
$('[placeholder]').focus(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
input.removeClass('placeholder');
}
}).blur(function() {
var input = $(this);
if (input.val() == '' || input.val() == input.attr('placeholder')) {
input.addClass('placeholder');
input.val(input.attr('placeholder'));
}
}).blur().parents('form').submit(function() {
$(this).find('[placeholder]').each(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
}
})
});
I simplified your HTML code to the following:
<form name="loginForm" method="post" onsubmit="return validateForm();" action="index.php">
<label>Email Address: <input type="email" name="email" autocomplete="off" placeholder="Email Address"/></label>
<label>Password: <input type="password" name="password" placeholder="Password"/></label>
<button type="submit" class="button large arrow-type-2 dark">Log In</button>
</form>
<form name="registerForm" method="post" onsubmit="return validatethisForm();"
action="index.php">
<label>Email Address: <input type="email" name="email" autocomplete="off" placeholder="Email Address"/></label>
<label>Password: <input type="password" name="password" placeholder="Password"/></label>
<button type="submit" class="button large arrow-type-2 dark">Create Free Account</button>
</form>
Points
Always include a label. Not all browsers support HTML5 placeholders.
All IDs here are reluctant. Forms can be accessed by
var loginForm = document.forms.loginForm; //By name
and form elements by
loginForm.email; //Also by name
No need for divs and brs to manage the line breaks. Use the labels themselves. Add display: block; as necessary.
Don't use inline style attribute. Use a CSS <style> element or an external stylesheet.
There's no AutoComplete on password fields.
Use HTML5's new form input types. type="email" will have the browser natively validate the field and notify the user if the email is not valid.
Keep it simple. No need for bloating.
Since both functions do the same thing, just make one function and bind it to both forms 'onsubmit' event.
You taggued is as jquery ,so, jquery-style, using Mike Alsup's jQuery Form Plugin.
function validate(formData, jqForm, options) {
// formData is an array of objects representing the name and value of each field
// that will be sent to the server; it takes the following form:
//
// [
// { name: username, value: valueOfUsernameInput },
// { name: password, value: valueOfPasswordInput }
// ]
//
// To validate, we can examine the contents of this array to see if the
// username and password fields have values. If either value evaluates
// to false then we return false from this method.
for (var i=0; i < formData.length; i++) {
if (!formData[i].value) {
alert('Please enter a value for both Username and Password');
return false;
}
}
alert('Both fields contain values.');
}
$('form').ajaxForm( { beforeSubmit: validate } );
This example and more info here.