preventDefault() cause problem on validating the form - javascript

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

Related

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

How to disable submit button until all mandatory fields are filled using html and vanilla js

How to disable submit button until the user enters all fields and also how to use event listener on submit form.
<form action='index.html' id="form-user" onsubmit="init()">
<input type="text" name="username" id="username" placeholder="username">
<input type="email" name="email" id="email" placeholder="email">
<input type="password" name="password" id="password" placeholder="password">
<button type="submit" name="submit" id='button-send'>SUBMIT</button>
</form>
const init = function () {
let username = document.getElementById("username").value;
let password = document.getElementById("password").value;
let email = document.getElementById("email").value;
alert(username,password,email)
};
Jsfiddle link
Set up a validation object with booleans to record if all your values have met validation.
Then I'd loop through all your inputs and add an event listener to each of them. In this example I've checked to see if each has at least one character in them, but you might want to expand on this.
Finally, loop through your validation object and check if all the values are true. If they are, remove the disabled attribute from the button.
let inputs = document.querySelectorAll('input');
let buttonSend = document.getElementById('button-send');
let inputValidator = {
"username": false,
"email": false,
"password": false
}
inputs.forEach((input) => {
input.addEventListener('input', () => {
let name = event.target.getAttribute('name');
if (event.target.value.length > 0) {
inputValidator[name] = true;
} else {
inputValidator[name] = false;
};
let allTrue = Object.keys(inputValidator).every((item) => {
return inputValidator[item] === true
});
if (allTrue) {
buttonSend.disabled = false;
} else {
buttonSend.disabled = true;
}
})
})
<form action='index.html' id="form-user">
<input type="text" name="username" id="username" placeholder="username">
<input type="email" name="email" id="email" placeholder="email">
<input type="password" name="password" id="password" placeholder="password">
<button type="submit" name="submit" id='button-send' disabled>SUBMIT</button>
</form>
This is probably not what you are looking for but you can achieve almost the same effect by simply using the required attribute in your input fields:
<form action='index.html' id="form-user">
<input type="text" name="username" id="username" placeholder="username" required>
<input type="email" name="email" id="email" placeholder="email" required>
<input type="password" name="password" id="password" placeholder="password" required>
<button type="submit" name="submit" id='button-send' >SUBMIT</button>
</form>
Using the onBlur event will ensure the user has visited each field. You may also want to check the field contains a value, for that you can add the HTML required attribute.
var isDirty = {
username: false,
password: false,
email: false
}
const init = function() {
let incompleteItems = getIncompleteItems();
if(incompleteItems.length > 0) {
alert(`${incompleteItems} requires a value.`);
return;
}
let username = document.getElementById("username").value;
let password = document.getElementById("password").value;
let email = document.getElementById("email").value;
alert(`values: ${username}, ${email}, ${password}`);
};
const onChange = function(e) {
isDirty[e.id] = true;
}
const getIncompleteItems = function() {
let incomplete = "";
for (const [key, value] of Object.entries(isDirty)) {
if(value === false) {
if(incomplete.length > 0) {
incomplete += `, ${key}`;
}
else {
incomplete = key;
}
}
}
return incomplete;
}
<form method='GET' id="form-user" onsubmit="init()">
<input type="text" name="username" id="username" placeholder="username" onBlur="onChange(this)">
<input type="email" name="email" id="email" placeholder="email" onBlur="onChange(this)">
<input type="password" name="password" id="password" placeholder="password" onBlur="onChange(this)">
<button type="submit" name="submit" id='button-send'>SUBMIT</button>
</form>
Create a validation function which will check all the validations and sets the disabled property of the button if validation fails and vice versa. Call the validation function on every change of all the fields.
You can use oninput event
<input type="text" oninput="validate()">

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

Submitting form even when validation regex is wrong

i am having this problem when i submit the form where both the password and username is wrong. I get an alert box saying that i have enter the wrong details. But when the username is correct and password is validation is wrong it will give me an arlet box by when pressed ok it will submit the form even when i have returned false.
Help please much appreciated
<script type="text/javascript">
function validate(form_id, firstName, password){
var Reg = /^[A-Za-z0-9_]{1,20}$/;
var Reg1 = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/;
var username = document.forms[form_id].elements[firstName].value;
var password = document.forms[form_id].elements[password].value;
if (Reg.test(username) == false) {
alert('Invalid Username.');
document.forms[form_id].elements[firstName].focus();
return false;
}
if (Reg1.test(password) == false) {
alert('Invalid Password.');
document.forms[form_id].elements[password].focus();
return false;
}
}
</script>
<form id="form_id" action="userlogininput.cgi" onsubmit="javascript:return validate('form_id','firstName','password');" name="form" method="post">
Username : <input type="text" id="firstName" name="firstName" class="textboxH-300" required><br>
Password : <input type="password" id="password" name="password" class="textboxH-300" required><br><br>
<input id="submitbtn" type="submit" value="Submit"/>
</form>
You can use e.preventDefault() to prevent form sending.
Here is a code example
(function(){
function validate(e) {
e.preventDefault(); // prevent the form sending
var Reg = /^[A-Za-z0-9_]{1,20}$/;
var Reg1 = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/;
var username = document.getElementById('firstName');
var password = document.getElementById('password');
if (Reg.test(username.value) == false) {
alert('Invalid Username.');
username.focus();
return false;
}
if (Reg1.test(password.value) == false) {
alert('Invalid Password.');
password.focus();
return false;
}
}
//add event listener for form submission
document.getElementById('form_id').addEventListener('submit',validate);
})();
<form id="form_id" action="userlogininput.cgi" name="form" method="post">
Username :
<input type="text" id="firstName" name="firstName" class="textboxH-300" required>
<br> Password :
<input type="password" id="password" name="password" class="textboxH-300" required>
<br>
<br>
<input id="submitbtn" type="submit" value="Submit" />
</form>
Try prevent default event.
Bind function to the form submit event:
function validate(form){
var Reg = /^[A-Za-z0-9_]{1,20}$/;
var Reg1 = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/;
var username = form.querySelector('[name=firstName]');
var password = form.querySelector('[name=password]');
if (Reg.test(username.value) == false) {
event.preventDefault();
alert('Invalid Username.');
username.focus();
return false;
}
if (Reg1.test(password.value) == false) {
event.preventDefault();
alert('Invalid Password.');
password.focus();
return false;
}
}
<form onsubmit="validate(this)">
<input name="firstName">
<br>
<input name="password">
<br>
<button type="submit">submit</submit>
</form>

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