Can't insert spaces in my text input - javascript

I have a form with 3 text inputs, the problem is, when I want to insert a space it doesn't allow me to. My code is:
<form action="post.php" name="MYFORM" id="MYFORM" method="post">
<label>Name</label>
<input name="name" size="30" type="text" id="name">
<br clear="all" />
<label>Email</label>
<input name="email" size="30" type="text" id="email">
<br clear="all" />
<label>Message</label>
<textarea id="message" name="message"></textarea>
<br clear="all" /><br clear="all" />
<label> </label>
<input value="Send" type="submit" id="Send">
When it submits it is validated by a javascript file and afterwards mailed by a php file, but I dont think that matters.
PROBLEM: cant add spaces in these text inputs.
Thanx in advance
EDIT: JAVASCRIPT CODE:
$(document).ready(function() {
$('#Send').click(function() {
// name validation
var nameVal = $("#name").val();
if(nameVal == '') {
$("#name_error").html('');
$("#name").after('<div class="errorwrapper"><label class="error" id="name_error">Please enter your name.</label></div>');
return false
}
else
{
$("#name_error").html('');
}
/// email validation
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var emailaddressVal = $("#email").val();
if(emailaddressVal == '') {
$("#email_error").html('');
$("#email").after('<div class="errorwrapper"><label class="error" id="email_error">Please enter your email address.</label></div>');
return false
}
else if(!emailReg.test(emailaddressVal)) {
$("#email_error").html('');
$("#email").after('<div class="errorwrapper"><label class="error" id="email_error">Enter a valid email address.</label></div>');
return false
}
else
{
$("#email_error").html('');
}
var mesVal = $("#message").val();
if(mesVal == '') {
$("#mes_error").html('');
$("#message").after('<div class="errorwrapper"><label class="error" id="mes_error">Please enter a message.</label></div>');
}
else
{
$("#after_submit").html('');
$("#Send").after('<label class="success" id="after_submit">Your message has been submitted.</label>');
$("#after_submit").fadeOut(9000);
$("#mes_error").html('');
clear_form();
}
return false;
})
function clear_form()
{
$("#name").val('');
$("#email").val('');
$("#message").val('');
$(".errorwrapper").empty();
}
});

I would have never figured it out if i wouldnt have seen an other person with an error in using a keyboard controlled javascript slideshow. Sry if i caused you guys wasting some time.
I was using fadeslideshow 2.0 by Pascal Bajorat.

Related

preventDefault() cause problem on validating the form

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

Form Validation in JQuery Mobile

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..

The onsubmit event handler javascript not working

I have a problem. When I clicked the submit button nothing happens, even when I filled out the username and password with numbers (I don't want the username and password contains any number so I did make the condition for it), there is no alert display. I do not know where the problem comes from? Can you guys help me with this
Note: the reset function works fine
function validateInput() {
var firstName = document.forms["sign_up"]["firstName"];
var lastName = document.forms["sign_up"]["lastName"];
var email = document.forms["sign_up"]["email"];
var reg = /^[a-zA-Z]+$/;
if (firstName.value !== '' || lastName.value !== '' || email.value !== '') {
if (firstName.value.match(reg) && lastName.value.match(reg)) {
alert("Form is submitted");
// return true;
return false; // for the demo, so it doesn't submit
} else {
if (firstName.value.match(reg) === false) {
document.getElementById("error").innerHTML = "Numbers are not allowed in username";
return false;
} else if (lastName.value.match(reg) === false) {
document.getElementById("error").innerHTML = "Numbers are not allowed in password";
return false;
}
}
}
}
function reset() {
document.getElementById("first").innerHTML = "";
document.getElementById("last").innerHTML = "";
document.getElementById("email").innerHTML = "";
}
<form id="sign_up" onsubmit="return validateInput()">
<p id="error"></p>
<label for="firstName">First Name</label>
<input type="text" id="firstName" value="" placeholder="Enter your first name">
<label for="lastName">Last Name</label>
<input type="text" id="lastName" value="" placeholder="Enter your last name">
<label for="email">Email</label>
<input type="email" id="email" value="" placeholder="Enter your email">
<button type="submit">Submit</button>
<button type="button" onclick="reset();">Cancel</button>
</form>
Use the Pattern attribute in input for validation like below
<input type="text" id="firstName" value="" pattern="[^0-9]*" title="Numbers are not allowed" placeholder="Enter your first name">
for more references: https://www.w3schools.com/tags/att_input_pattern.asp
And for reset functionality use reset
<input type="reset" value="reset">
It's better than create a special function for it and it saves your number of lines:-)
First, try to avoid to inline event handlers as they are not rec-emended at all. Also to reset form values you can simply use reset() method on the form.
Also, do not use innerHTML just to set the text of your error. You can use textContent instead which is better fit in your example.
You can use addEventListener with submit event to check for validation on your firstname and lastname.
I have fixed your code and its all working as expected.
Live Working Demo:
let form = document.getElementById("sign_up")
var firstName = document.getElementById("firstName")
var lastName = document.getElementById("lastName")
var email = document.getElementById("email")
var reset = document.getElementById("clearValues")
var reg = /^[a-zA-Z]+$/;
form.addEventListener('submit', function(e) {
e.preventDefault()
if (firstName.value != '' || lastName.value != '' || email.value != '') {
if (firstName.value.match(reg) && lastName.value.match(reg)) {
alert("Form is submitted");
} else if (!firstName.value.match(reg)) {
document.getElementById("error").textContent = "Numbers are not allowed in username";
} else if (!lastName.value.match(reg)) {
document.getElementById("error").textContent = "Numbers are not allowed in password";
}
}
})
reset.addEventListener('click', function(e) {
document.getElementById("sign_up").reset();
})
input {
display:block;
}
<head>
</head>
<body>
<form id="sign_up" action="#">
<p id="error"></p>
<label for="firstName">First Name</label>
<input type="text" id="firstName" value="" placeholder="Enter your first name">
<label for="lastName">Last Name</label>
<input type="text" id="lastName" value="" placeholder="Enter your last name">
<label for="email">Email</label>
<input type="email" id="email" value="" placeholder="Enter your email">
<button type="submit">
Submit
</button>
<button type="button" id="clearValues" onclick="reset();">
Cancel
</button>
</form>
</body>
You don't need to return a function in onsubmit event. This should work fine.
<form id="sign_up" onsubmit="validateInput()">
Reference:
https://www.w3schools.com/jsref/event_onsubmit.asp

Multiple IF statements showing image when input are completed

I cant seem to get multiple IF statements to work on my script. I want an image to appear when three input fields have text in, and not when only one or two have text in. Any help would be much appreciated.
HTML:
<form method="post" action="email-case-study-checker.php" onsubmit="return submitToHighslide(this)">
Full Name <span class="required">*</span><br />
<input name="your_name" type="text" id="name" title="Enter your full name" size="36" maxlength="50"><br /><br />
Company <span class="required">*</span><br />
<input name="your_company" type="text" id="company" title="Enter your company name" size="36" maxlength="50"><br /><br />
Email Address <span class="required">*</span><br />
<input name="your_email" type="text" id="email" title="Enter your email address" size="36" maxlength="50"><br /><br />
<div id="hiddenpdf"> Right click and save link as to download pdf</div>
Javascript:
<script>
function hiddenpdf()
{
if(document.getElementById('name').value == "") {
if(document.getElementById('company').value == "") {
if(document.getElementById('email').value == "");}
{
document.getElementById('hiddenpdf').style.display = 'none';
}
}
else
{
document.getElementById('hiddenpdf').style.display = 'block';
}
}
</script>
if (document.getElementById('name').value != "" && document.getElementById('company').value != "" && document.getElementById('email').value != ""){
document.getElementById('hiddenpdf').style.display = 'block';
}else{
document.getElementById('hiddenpdf').style.display = 'none';
}
Hope this helps.
You have a syntax error in your code. Above solution checks with "and" logic and will only execute 'block' statement if all three conditions are met otherwise it will move over to else statement.

using id="submit" twice on one page

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.

Categories