<div class="form-style-5">
<form action="send-sms.php" method="POST">
<fieldset>
<legend><span class="number">1</span> Your Information</legend>
<input type="text" name="field1" id="name" placeholder="Your Name *">
<input type="email" name="field2" id="contact"placeholder="Contact Information (Email, Phone Number, etc.) *">
<input type="location" name="field3" id="location" placeholder="Your Location (i.e. McNutt, Hodge Hall, exact address, etc.)*">
<input type="text" name="field4" id="misc" placeholder="Miscellaneous Information That May Be Important"></textarea>
<label for="job">Urgency:</label>
<select id="job" name="field5">
<optgroup label="Urgency level: just for us to prioritize properly">
<option value="Not Urgent">Low (ETA: Up to an hour)</option>
<option value="reading">Normal (ETA: Up to 45 mins)</option>
<option value="boxing">Critical (ETA: ASAP!)</option>
</optgroup>
</select>
</fieldset>
<fieldset>
<legend><span class="number">2</span>Task that needs completion</legend>
<input type="text" id="task" name="field6" placeholder="Let Us Know How We Can Help!*"></input>
</fieldset>
<input name="submit" type="submit" value="Submit" onClick="push();validateForm();"/>
</form>
</div>
I'm using simple JS validation function which gets called "onClick" my submit button. My error messages get displayed correctly if someone submits an empty form, however, once you press "OK" on that alert, the form still gets submitted. I have a similar validation system on a different form and it runs smoothly.... Any modifications to my code, even if it doesn't solve the overall problem, would be appreciated.
function validateForm() {
var errormessage = "";
if (document.getElementById('name').value == "") {
errormessage += "Please enter your name. \n";
document.getElementById('name').style.borderColor = "red";
}
if (document.getElementById('contact').value == "") {
errormessage += "Please enter your contact. \n";
document.getElementById('contact').style.borderColor = "red";
}
if (document.getElementById('location').value == "") {
errormessage += "Tell us where to come! \n";
document.getElementById('location').style.borderColor = "red";
}
if (document.getElementById('task').value == "") {
errormessage += "Tell us how we can help! \n";
document.getElementById('task').style.borderColor = "red";
}
if (errormessage != "") {
alert(errormessage);
return false;
}
return true;
};
In order to prevent the form submission, the event must be stopped. The click handler setup will bubble to submission because it does not provide a way to stop the event.
An easy way is returning false, as you have attempted in the shown function. However, that return value is not being used. Note that your inline event handler looks like this
onClick="push();validateForm();"
As the value from validateForm is never used, the event handler continues on after the call to validation. The fix is to use the return value
onClick="push();return validateForm();"
Which will now properly stop the event if validation fails.
Related
I am trying to make a very simple login page for a website I created and I am having issues with the submit button. I got the submit button to work fine if I use a "button" type in HTML however the Enter key does not work then. I discovered if I use a "submit" type, the Enter button and the mouse click will work however... the button now goes over my IF statement, straight to my Else statement. Any help would be appreciated.
HTML form:
<form>
<label for="pswd">ENTER PASSWORD</label>
<br>
<input class="box" type="password" id="pswd">
<br>
<input class="confirm" type="submit" value="SUBMIT" onclick="checkPswd();" />
</form>
JS code:
function checkPswd() {
var confirmPassword = "08012020";
var password = document.getElementById("pswd").value;
if (password == confirmPassword) {
window.location = "index.html";
} else {
alert("Password is incorrect, Please try again.")
}
}
Again, thank you in advance...
The key is returning false after calling your function, so the page redirect is not triggered by the input submission:
function checkPswd() {
let confirmPassword = "08012020";
let password = document.getElementById("pswd").value;
if (password === confirmPassword) {
alert("CORRECT!");
} else{
alert("Password is incorrect, Please try again.")
}
}
<form>
<label for="pswd">ENTER PASSWORD</label>
<br>
<input class="box" type="password" id="pswd">
<br>
<input class="confirm" type="submit" value="SUBMIT" onclick="checkPswd(); return false;" />
</form>
I would like to add that performing client-side password checking is very insecure since the source code can easily be inspected, so if you are hoping to use this in a real website I would suggest you consider a different approach!
So I made a code that reads the name and password form in html. In java script I made code to ensure that the name and password fields are filled in. It also records that if the password value is less than or equal to 6 a message would display "Password must be longer than 6 characters" and if the password value is greater than or equal to 15 a message would display "Password must be shorter than 15 characters" (extra: for whatever reason when I put a 6 character password it would display that message despite the operator I included same goes for the latter).
Here's the HTML Code Followed by the javascript:
<!--Error container-->
<div id="error"></div>
<!--Form-->
<form id="form" action="/" method="GET">
<fieldset>
<!--Legend-->
<legend>Form: </legend>
<!--Name-->
<label for="name">Name:</label>
<input type="text" name="Name" id="name">
<br><br>
<!--Password-->
<label>Password: </label>
<input type="password" name="password" id="password">
<br><br>
<!--Submit and Reset Button-->
<input type="submit" Value="Submit">
<input type="reset" Value="Reset">
</fieldset>
</form>
<!--form-->
[Filler text: I thought I made the question as simplistic and easy to follow as it needs to be]
Here's the javascript portion.
The first four lines gets the id from the html code dropped from above and then the magic happens from there.
const name = document.getElementById('name')
const password = document.getElementById('password')
const form = document.getElementById('form')
const errorElement = document.getElementById('error')
form.addEventListener('submit', (e) =>{
let messages = []
if(name.value === '' || name.value == null){
messages.push("Name is required")
}
if(password.value.length <= 6){
messages.push("Password must be longer than 6 characters")
}
if(password.value.length >= 15){
messages.push("Password must be shorter than 15 characters")
}
if(messages.length > 0){
e.preventDefault()
errorElement.innerText = messages.join(', ')
}
e.preventDefault()
})
Please stick to Javascript and html
And thank you for using your time to read and lend a hand.
Your form won't submit because you're actively preventing it from doing so using e.preventDefault()
I would either just remove that or trigger a submit action via JavaScript if no errors occur:
if (!messages) //the variable messages is empty, so there are no errors
form.submit() //submit the form
This might also help you:
How can I submit a form using JavaScript?
Just a few minor things:
<= 6 is what's causing it to still show the error message when it's exactly 6 characters. Updating it to < 6 will only show the message when the password is less than 6 characters (as opposed to less than or equal to)
The e.preventDefault() is still being called, even outside of the error check
The messages array is never reset, so even once the user has fixed all errors, the form is still being prevented from submitting
Here's an updated version:
const name = document.getElementById('name')
const password = document.getElementById('password')
const form = document.getElementById('form')
const errorElement = document.getElementById('error')
form.addEventListener('submit', (e) =>{
let isValid = true;
let messages = []
if(name.value === '' || name.value == null){
messages.push("Name is required");
isValid = false;
} else if(password.value.length < 6){
messages.push("Password must be longer than 6 characters");
isValid = false;
} else if (password.value.length >= 15){
messages.push("Password must be shorter than 15 characters");
isValid = false;
}
if(!isValid){
e.preventDefault()
errorElement.innerText = messages.join(', ')
}
})
<!--Error container-->
<div id="error"></div>
<!--Form-->
<form id="form" action="/" method="GET">
<fieldset>
<!--Legend-->
<legend>Form: </legend>
<!--Name-->
<label for="name">Name:</label>
<input type="text" name="Name" id="name">
<br><br>
<!--Password-->
<label>Password: </label>
<input type="password" name="password" id="password">
<br><br>
<!--Submit and Reset Button-->
<input type="submit" Value="Submit">
<input type="reset" Value="Reset">
</fieldset>
</form>
<!--form-->
Side note: In real life, you never want to restrict the length of the users password. Let them make it as strong as they like. You're going to hash it anyway, so length and special characters won't be an issue for storage.
I have this code to validate inputs:
<script>
function validate()
{
var firstName = document.form.fullname.value;
var lastName = document.form.fullname.value;
var email = document.form.email.value;
var password = document.form.password.value;
var conpassword = document.form.conpassword.value;
if (firstName == null || firstName == "")
{
alert("Firstname can't be blank");
return false;
} else if (lastName == null || lastName == "")
{
alert("Lastname can't be blank");
return false;
} else if (email == null || email == "")
{
alert("Email can't be blank");
return false;
} else if (password.length < 6)
{
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
And this is my form:
<form name="form" action="<%=request.getContextPath()%>/register" method="post">
<div class="container">
<div class="left">
<div class="header">
<h2 class="animation a1">Register now</h2>
<h4 class="animation a2">Enter information in field and create account!</h4>
</div>
<div class="form">
<input type="text" name="firstName" class="form-field animation a3" placeholder="Name...">
<input type="text" name="lastName" class="form-field animation a3" placeholder="Last name...">
<input type="email" name="email" class="form-field animation a3" placeholder="Email adress...">
<input type="password" name="password" class="form-field animation a4" placeholder="Password">
<button class="animation a6" value="Submit" type="submit">REGISTER</button>
</div>
</div>
<div class="right"></div>
</div>
</form>
How to implement that function to my form? Because now when I click submit, in my database an empty user is added. I want to add that it throws out an error in each field if it is not validly filled in
You can get the validate function to execute by adding an 'onsubmit' to your form html tag ( see here w3 Schools for executing a function on submit: onsubmit in forms)
As for the errors, when executing the code, the function cannot read a property 'value' of undefined. So what is happening is that you are telling the validate function to get parts out of the form out that it cannot find (fullname and conpassword are not defined).
Take a look at your form's name tags for fields and then reference those names in the validate function. So when declaring firstName instead of document.form.fullname.value try document.form.firstName.value referring in the form. Do this for first and last name using their names in the form, and also get rid of (or comment out) the conpassword variable.
This validation could be done without javascript function. Use the "required" tag for the inputs which are mandatory.
For example :
<input type="text" name="firstName" class="form-field animation a3" placeholder="Name..." required>
In case of password you may use the pattern attribute.
If you need to use javascript in particular, then go for onclick in the button tag.
<button class="animation a6" onclick="validate()">REGISTER</button>
and include the form submit in the javascript function -
document.form.submit();
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.
I've tried, I've researched, and I still can't figure out how to validate this form using jQuery. I've even tried to check out the jQuery API and I had no luck with it. This shouldn't be as hard as it seems. There are a few id's that i'm not using yet because I want to get what I have so far working before I continue. The best I could find for validating emails is just straight up JavaScript. Here's my code.
$(document).ready(function(){
$("#sendForm").click(function(){
var validForm=true; //set valid flag to true, assume form is valid
//validate customer name field. Field is required
if($("#custName").val()) {
$("#custNameError").html(""); //field value is good, remove any error messages
} else {
$("#custNameError").html("Please enter your name.");
validForm = false;
}
//validate customer phone number. Field is required, must be numeric, must be 10 characters
var inPhone = $("#custPhone").val(); //get the input value of the Phone field
$("#custPhoneError").html(""); //set error message back to empty, assume field is valid
if(!inPhone) {
$("#custPhoneError").html("Please enter your phone number.");
validForm = false;
} else {
//if( !$.isNumeric(inPhone) || Math.round(inPhone) != inPhone ) //if the value is NOT numerice OR not an integer. Rounding technique
if( !$.isNumeric(inPhone) || (inPhone % 1 != 0) ) //if the value is NOT numerice OR not an integer. Modulus technique
{
$("#custPhoneError").html("Phone number must be a number.");
validForm = false;
} else {
if(inPhone.length != 10) {
$("#custPhoneError").html("Phone number must have 10 numbers");
validForm = false;
}
}
}
//ALL VALIDATIONS ARE COMPLETE. If all of the fields are valid we can submit the form. Otherwise display the errors
if(validForm) {
//all values are valid, form is good, submit the form
alert("Valid form will be submitted");
//$("#applicationForm").submit(); //SUBMIT the form to the server
} else {
//form has at least one invalid field
//display form and associated error messages
alert("Invalid form. Display form and error messages");
}
}); //end sendform.click
}); //end .ready
function isEmail(email) {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
label {
width:150px;
display:inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h2></h2>
<h3>Form Validation Project - Complaint Form</h3>
<form id="form1" name="form1" method="post" action="">
<p>Please enter the following information in order to process your concerns.</p>
<p>
<label for="custName">Name:</label>
<input type="text" name="custName" id="custName" />
<span id="custNameError" class="errorMsg"></span>
</p>
<p>
<label for="custPhone">Phone Number: </label>
<input type="text" name="custPhone" id="custPhone" />
<span id="custPhoneError" class="errorMsg"></span>
</p>
<p>
<label for = "email">Email:</label>
<input type = "text" name = "emailAdd" id = "emailAdd" />
<span id = "emailError" class = "emailError"></span>
</p>
<p>Please Select Product Group:</p>
<p>
<label>
<input type="radio" name="custProducts" value="books" id="custProducts_0" />
Books
</label>
<br />
<label>
<input type="radio" name="custProducts" value="movies" id="custProducts_1" />
Movies
</label>
<br />
<label>
<input type="radio" name="custProducts" value="electronics" id="custProducts_2" />
Consumer Electronics
</label>
<br />
<label>
<input type="radio" name="custProducts" value="computer" id="custProducts_3" />
Computer
</label>
<br />
</p>
<p>Description of problem: (Limit 200 characters)</p>
<p>
<label for="custComplaint"></label>
<textarea name="custComplaint" id="custComplaint" cols="45" rows="5"></textarea>
</p>
<p>
<input type="submit" name="button" id="button" value="File Complaint" />
<input type="reset" name="button2" id="button2" value="Reset" />
</p>
</form>
<p> </p>
$("#button").click(function(e){
e.preventDefault(); // you need to stop the initial event to have a chance to validate
var validForm=true;
// etc...
You can use jquery.validate.js to validate your forms , it will overcome all your manual efforts to create the validation rules also it is providing the various predefined rules like required,email, minlength and maxlength, etc. So, it will be easier for you to achieve what you need very easily.
https://jqueryvalidation.org/
I have a simple jquery form validation and submission package - see if that's of any help - it's easy to install and you can customise quite a few things: https://github.com/sebastiansulinski/ssd-form
Just to get you started, your submit control in the html has id "button", so you should use $('#button').click, not $('#sendForm').click.
Also, if you want to stay on the page (like to do validations, show errors, etc), you have to prevent the form from submitting automatically when the button is clicked. There are lots of ways to do this, but the easiest way is to just change your button type from submit to button. Ie, replace this:
<input type="submit" name="button" id="button" value="File Complaint" />
with this:
<input type="button" name="button" id="button" value="File Complaint" />
------
That should get you started, at least your code will run, you can use console.log to debug, etc. Good luck.
UPDATE
I should add that if you take my advice, the form will never submit on it's own - that is good if some validation fails and you want to stay on the page and give some error feedback to the user.
When you do want the form to submit, you have to make it happen yourself. Again, there are lots of ways to do this, but the simplest one is probably:
$('#form1').submit();