Okay, I'm trying to get a contact form to work and it is, sort of. The data is passing through, but I can't get the jQuery to work. If I type in two different email addresses it doesn't catch it. Here is the relevant code I used:
HTML
<aside>
<form action="sendmail.php" method="post" name="contact_form" id="contact_form">
<fieldset>
<legend>sign up now!</legend><br>
<p>Sign up for my email list and get a free mini coloring book!</p><br>
<img src="Images/minicoloirngbook.jpg" alt="mini coloring book"><br>
<label for="name"> Name:</label>
<input type="text"name="name" id="name" required><span>*</span><br>
<label for="email">Email Address:</label>
<input type="email" name="email" id="email" required><span>*</span><br>
<label for="verify">Verify Email:</label>
<input type="email" name="verify" id="verify" required> <span>*</span><br>
<div id="buttons">
<input type="submit" id="submit" value="Sign Up">
</div>
</fieldset>
</form>
</aside>
and here is the Javascript:
$("#contact_form").submit(event => {
let isValid = true;
// validate the first name entry
const name = $("#name").val().trim();
if (name == "") {
$("#name").next().text("This field is required.");
isValid = false;
} else {
$("#name").next().text("");
}
$("#name").val(name);
// validate the email entry with a regular expression
const emailPattern = /\b[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b/;
const email = $("#email").val().trim();
if (email == "") {
$("#email").next().text("This field is required.");
isValid = false;
} else if ( !emailPattern.test(email) ) {
$("#email").next().text("Must be a valid email address.");
isValid = false;
} else {
$("#email").next().text("");
}
$("#email").val(email);
// validate the verify entry
const verify = $("#verify").val().trim();
if (verify == "") {
$("#verify").next().text("This field is required.");
isValid = false;
} else if (verify !== email) {
$("#verify").next().text("Must match first email entry.");
isValid = false;
} else {
$("#verify").next().text("");
}
$("#verify").val(verify);
// prevent the submission of the form if any entries are invalid
if (isValid == false) {
event.preventDefault();
}
}),
I think that the answer is probably something really simple that I can't see and would appreciate your help in figuring it out.
This should do it. Here is the jsfiddle if you like to play with the code: https://jsfiddle.net/bogatyr77/xk6ez3aq/7/
$("form").submit(function(e) {
var name = $("#a").val();
if (name == "") {
$("#nameerror").text("This field is required.");
alert('false');
} else {
alert('true');
$("#nameerror").remove();
}
//email1
var emailPattern = /\b[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b/;
const email = $("#b").val();
if (email == "") {
$("#email1error").text("This field is required.");
isValid = false;
} else if (!emailPattern.test(email)) {
$("#email1error").text("Must be a valid email address.");
isValid = false;
} else {
$("#email1error").remove();
}
//eamil 2
var verify = $("#c").val();
if (verify == "") {
$("#email2error").text("This field is required.");
isValid = false;
} else if (verify !== email) {
$("#email2error").text("Must match first email entry.");
isValid = false;
} else {
$("#email2error").remove();
}
if (isValid == false) {
event.preventDefault();
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="javascript:alert('ok')">
<label for="name"> Name:</label>
<input type="text" name="name" id="a"><span>*</span>
<div id="nameerror"></div><br>
<label for="email">Email Address:</label>
<input type="text" name="email" id="b"><span>*</span>
<div id="email1error"></div><br>
<label for="verify">Verify Email:</label>
<input type="text" name="verify" id="c"> <span>*</span>
<div id="email2error"></div><br>
<input type="submit" value="submit" />
</form>
<div></div>
Related
I'm trying to use javascript regular expressions for my email input area. I've tried each of the following:
/^\S+#\S+$/
/\S+#\S+\.\S+/
/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/
Neither of them work, and every other input field works fine. Here is my Javascript and html:
function checkForm(){
var isValid = true;
var name = document.forms['contact']['name'].value;
var email = document.forms['contact']['email'].value;
var emailpattern = /^\S+#\S+$/;
var subject = document.forms["contact"]["subject"].value;
var textarea = document.forms["contact"]["textarea"].value;
if(name == ""){
document.getElementById('nameMessage').innerHTML = "please enter a name";
isValid = false;
} else {
document.getElementById('nameMessage').style.display = "none";
}
if(!emailpattern.test(emailMessage)){
document.getElementById('emailMessage').innerHTML = "please enter a valid email";
isValid = false;
}
else {
document.getElementById('emailMessage').style.display = "none";
}
<form action="thankyou.html" id="contactId"name="contact" onsubmit="return checkForm()">
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<p id="nameMessage"></p>
<label for="email">Email:</label>
<input type="text" id="email" name="email">
<p id="emailMessage"></p>
<div><button type="submit" id="submit">Submit</button></div>
You are using emailMessage wrong variable to test regex use email
and also you have to return false if any validation fails to prevent form from submitting.
function checkForm(){
var isValid = true;
var name = document.forms['contact']['name'].value;
var email = document.forms['contact']['email'].value;
var emailpattern = /^\S+#\S+$/;
if(name == ""){
document.getElementById('nameMessage').innerHTML = "please enter a name";
isValid = false;
return false;
} else {
document.getElementById('nameMessage').style.display = "none";
}
if(!emailpattern.test(emailMessage)){
document.getElementById('emailMessage').innerHTML = "please enter a valid email";
isValid = false;
return false;
}
else {
document.getElementById('emailMessage').style.display = "none";
}
}
<form action="thankyou.html" id="contactId"name="contact" onsubmit="return checkForm()">
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<p id="nameMessage"></p>
<label for="email">Email:</label>
<input type="text" id="email" name="email">
<p id="emailMessage"></p>
<div><button type="submit" id="submit">Submit</button></div>
</form>
How can I make password field to check each other that the value written by user matches ?
function checkPassword(form) {
pOne = form.pOne.value;
pTwo = form.pTwo.value;
// If password not entered
if (pOne == '')
alert("Please enter Password");
// If confirm password not entered
else if (pTwo == '')
alert("Please enter confirm password");
// If Not same return False.
else if (pOne != pTwo) {
// alert ("\nPassword did not match: Please try again...")
document.querySelector(".submit").addEventListener("click", print)
function print() {
return document.querySelector(".pass").textContent = "Your password does not match!"
}
}
// If same return True.
else {
document.querySelector(".submit").addEventListener("click", print)
function print() {
return document.querySelector(".pass").textContent = "Your password match perfectly!"
}
}
}
<form class="formtwo" onsubmit="checkPassword(this)">
<input type="email" name="email" placeholder="Email"><br>
<input type="password" name="pOne" placeholder="Password">
<input type="password" name="pTwo" placeholder="Re-Type Password">
<p class="pass">djkakj</p>
<button type="submit" class="submit">Submit</button>
</form>
You need to add the event listener to the form submit before you test
window.addEventListener("load", function() {
document.getElementById("formtwo").addEventListener("submit", function(e) {
const pOne = this.pOne.value;
const pTwo = this.pTwo.value;
const pass = document.querySelector(".pass");
let errors = [];
// If password not entered
if (pOne == '') errors.push("Please enter Password");
if (pTwo == '') errors.push("Please enter confirm password");
if (pOne != pTwo) errors.push("Password did not match: Please try again...")
if (errors.length > 0) {
e.preventDefault(); // this will stop submission
alert(errors.join("\n"))
pass.textContent = "Your password does not match!"
return;
}
pass.textContent = "Your password match perfectly!"
})
})
<form id="formtwo">
<input type="email" name="email" placeholder="Email"><br>
<input type="password" name="pOne" placeholder="Password">
<input type="password" name="pTwo" placeholder="Re-Type Password">
<p class="pass">djkakj</p>
<button type="submit" class="submit">Submit</button>
</form>
You can check my solution. Hope it's easier to understand. There were some issues in your code.
If you want to prevent the form submit if the password doesn't match then you need to use event.preventDefault to prevent the default behaviour.
You can fire the submit event once and then check for your required values.
const form = document.querySelector('.formtwo');
form.addEventListener('submit', checkPassword);
function checkPassword(e) {
e.preventDefault();
let pOne = form.pOne.value;
let pTwo = form.pTwo.value;
// If password not entered
if (pOne == "") alert("Please enter Password");
// If confirm password not entered
else if (pTwo == "") alert("Please enter confirm password");
// If Not same return False.
else if (pOne != pTwo) {
document.querySelector(".pass").textContent =
"Your password does not match!";
}
// If same return True.
else {
document.querySelector(".pass").textContent =
"Your password match perfectly!";
// submitting form
form.submit();
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<form class="formtwo">
<input type="email" name="email" placeholder="Email"><br>
<input type="password" name="pOne" placeholder="Password">
<input type="password" name="pTwo" placeholder="Re-Type Password">
<p class="pass">Password matching status</p>
<button type="submit" class="submit">Submit</button>
</form>
</body>
</html>
<script>
var password= document.forms["PestControl"]["password"].value;
var confirmpassword= document.forms["PestControl"]["confirmpassword"].value;
function validateForm() {
//alert('inside');
if(!validatePassword()){
alert("password did not matched or blank password fields");
document.forms["PestControl"]["password"].focus();
return false;
}
else if($.trim(password) != $.trim(confirmpassword)){
alert("password did not matched");
document.forms["PestControl"]["password"].focus();
return true;
}
else {
document.PestControl.action = "medical_college_process.php?trans=addcollege";
document.PestControl.method = "post";
document.PestControl.submit();
}
}
function validatePassword(){
var password= document.forms["PestControl"]["password"].value;
var confirmpassword= document.forms["PestControl"]["confirmpassword"].value;
var Exist = false;
if((password.value === '') && (confirm_password.value==='')) {
alert();
Exist = false;
}
else if(password.value != confirm_password.value) {
Exist = false;
}
else {
Exist = true;
}
async:false;
return Exist;
}
</script>
<div class="form-group col-md-12" style="text-align: right;margin-top: 10px;">
<label style="margin-bottom: 0px;">Password</label>
<input id="password" type="password" class="form-control" name="password" value="">
</div>
<div class="form-group col-md-12" style="text-align: right;margin-top: 10px;">
<label style="margin-bottom: 0px;">Confirm Password </label>
<input id="confirm_password" type="password" class="form-control" name="confirmpassword" value="">
</div>
<div class="col-md-12" style="text-align: right;margin-top: 10px;">
<button type="button" id="button1" name="" onclick="return validateForm()" class="btn btn-w-m btn-primary">Save</button>
when i click on save button for password and confirm password i m getting an alert of password did not match or blank password for non-matching password as well as for matching password ...getting same alert message
when i click on save button for password and confirm password i m getting an alert of password did not match or blank password for non-matching password as well as for matching password ...getting same alert message
when i click on save button for password and confirm password i m getting an alert of password did not match or blank password for non-matching password as well as for matching password ...getting same alert message
when i click on save button for password and confirm password i m getting an alert of password did not match or blank password for non-matching password as well as for matching password ...getting same alert message
Please have a look at below code. It worked on my side.
function validatePassword(){
var password= document.forms["PestControl"]["password"];
var confirmpassword= document.forms["PestControl"]["confirmpassword"];
var Exist = false;
if((password.value === '') && (confirmpassword.value==='')) {
alert('no input');
Exist = false;
}
else if(password.value != confirmpassword.value) {
alert('wrong password');
Exist = false;
}
else {
alert('correct');
Exist = true;
}
async:false;
return Exist;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="PestControl">
User password:<br>
<input type="password" name="password"> <br>
User confirm password:<br>
<input type="password" name="confirmpassword">
<input type="button" value="save" onclick="validatePassword()">
</form>
function validatePassword(){
var password= document.getElementById("your pass id").value;
var confirmpassword= document.getElementById("confirm_password").value;
var Exist = false;
if((password === '') && (confirmpassword==='')) {
alert();
Exist = false;
}
else if(password != confirmpassword) {
Exist = false;
}
else {
Exist = true;
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
How to print error message under respective input field if left empty and error message must be removed when filled, how to proceed further i have not used javascript for validation earlier.
script code
function validateForm() {
var a = document.forms["student_reg"]["name"].value;
if (a == null || a == "") {
alert("Name must be filled out");
return false;
}
var b = document.forms["student_reg"]["email"].value;
if (b == null || b == "") {
alert("Email must be filled out");
return false;
}
var c = document.forms["student_reg"]["username"].value;
if (c == null || c == "") {
alert("Username must be filled out");
return false;
}
var d = document.forms["student_reg"]["password"].value;
if (d == null || d == "") {
alert("Password must be filled out");
return false;
}
var e = document.forms["student_reg"]["roll_no"].value;
if (e == null || e == "") {
alert("Roll no must be filled out");
return false;
}
}
html code is here
<body>
Login
<form name="student_reg" method="POST" action="" onsubmit="return validateForm()">
<p>NAME:</p>
<input type="text" name="name" value="" >
<span class="error"><p id="name_error"></p></span>
<p>EMAIL:</p>
<input type="text" name="email" value="" >
<span class="error"><p id="email_error"></p></span>
<p>USERNAME:</p>
<input type="text" name="username" value="" >
<span class="error"><p id="username_error"></p></span>
<p>PASSWORD:</p>
<input type="password" name="password" value="" >
<span class="error"><p id="password_error"></p></span>
<p>ROLL NO:</p>
<input type="number" name="roll_no" value="" >
<span class="error"><p id="roll_no_error"></p></span>
<br/>
<br/>
<br/>
<input type="submit" name="submit" value="submit">
</form>
</body>
You can try this code:
It will check errors and returns at last after displaying all error messages if any.
function validateForm() {
var error = 0;
var a = document.forms["student_reg"]["name"].value;
document.getElementById('name_error').innerHTML = '';
if (a == null || a == "") {
// alert("Name must be filled out");
error++;
document.getElementById('name_error').innerHTML = 'Name must be filled out';
}
var b = document.forms["student_reg"]["email"].value;
document.getElementById('email_error').innerHTML = '';
if (b == null || b == "") {
// alert("Email must be filled out");
error++;
document.getElementById('email_error').innerHTML = 'Email must be filled out';
}
var c = document.forms["student_reg"]["username"].value;
document.getElementById('username_error').innerHTML = '';
if (c == null || c == "") {
// alert("Username must be filled out");
error++;
document.getElementById('username_error').innerHTML = 'Username must be filled out';
}
var d = document.forms["student_reg"]["password"].value;
document.getElementById('password_error').innerHTML = '';
if (d == null || d == "") {
// alert("Password must be filled out");
error++;
document.getElementById('password_error').innerHTML = 'Password must be filled out';
}
var e = document.forms["student_reg"]["roll_no"].value;
document.getElementById('roll_no_error').innerHTML = '';
if (e == null || e == "") {
// alert("Roll no must be filled out");
error++;
document.getElementById('roll_no_error').innerHTML = 'Roll no must be filled out';
}
if(error>0) {
return false;
}
return true;
}
Keep all the name attributes in array and validate in loop. As your ID is related to name attribute, concatenate the name with _error to get the ID of the error placeholder.
function validateForm() {
var names = ['name', 'email', 'username', 'password', 'roll_no'];
var errorCount = 0;
names.forEach(function(el) {
var val = document.forms["student_reg"][el].value;
if (val == null || val == "") {
document.getElementById(el + '_error').textContent = el.toUpperCase().replace('_', ' ') + " must be filled out";
++errorCount;
}
});
if (errorCount) return false;
}
<form name="student_reg" method="POST" action="" onsubmit="return validateForm()">
<p>NAME:</p>
<input type="text" name="name" value="">
<span class="error"><p id="name_error"></p></span>
<p>EMAIL:</p>
<input type="text" name="email" value="">
<span class="error"><p id="email_error"></p></span>
<p>USERNAME:</p>
<input type="text" name="username" value="">
<span class="error"><p id="username_error"></p></span>
<p>PASSWORD:</p>
<input type="password" name="password" value="">
<span class="error"><p id="password_error"></p></span>
<p>ROLL NO:</p>
<input type="number" name="roll_no" value="">
<span class="error"><p id="roll_no_error"></p></span>
<br/>
<br/>
<br/>
<input type="submit" name="submit" value="submit">
</form>
You can iterate through all elements of the form student_reg to validate email and required and print error message under respective input field if no value was set:
const validateForm = () => {
const form = document.forms['student_reg'],
inputs = [...form.getElementsByTagName('input')],
errors = [...form.getElementsByClassName('error')],
regex = /\S+#\S+\.\S+/,
setErrorMsg = (str, msg) => `${str.replace('_', ' ')} ${msg}`
let countErrors = 0
inputs.forEach((input, index) => {
// clear all errors
(errors[index] || '').innerHTML = ''
// validate email
if (input.name === 'email' && !regex.test(input.value)) {
errors[index].innerText = setErrorMsg(input.name, 'should be valid')
countErrors++
}
// validate required
if (!input.value) {
errors[index].innerText = setErrorMsg(input.name, 'field is required')
countErrors++
}
})
return countErrors === 0
}
p {
font-size: 13px;
margin: 4px 0 0;
}
.error {
font-size: 12px;
padding: 6px 0 4px;
color: red;
display: block
}
.error:first-letter {
text-transform: uppercase
}
button {
margin-top: 8px;
font-size: 16px;
}
<form name="student_reg" method="POST" action="" onsubmit="return validateForm()">
<p>NAME:</p>
<input type="text" name="name" value="">
<span class="error"></span>
<p>EMAIL:</p>
<input type="text" name="email" value="">
<span class="error"></span>
<p>USERNAME:</p>
<input type="text" name="username" value="">
<span class="error"></span>
<p>PASSWORD:</p>
<input type="password" name="password" value="">
<span class="error"></span>
<p>ROLL NO:</p>
<input type="number" name="roll_no" value="">
<span class="error"></span>
<button>Submit</button>
</form>
simple form It hold the Span for the Error msg.The span Id is very important here.you need to make color for errors using css
<form id="loginform" name="loginform" action="" method="post">
<label>Name</label>
<input type="text" name="username" />
<p></p>
<span id="usernameError"></span>
<p></p>
<label>Pwd</label>
<input type="password" name="password" />
<p></p>
<span id="passwordError"></span>
<p></p>
<input type="submit" value="Submit" />
</form>
script
<script type="application/javascript">
window.onload = function(){
function handleinput(){
if(document.loginform.username.value == ""){
document.getElementById("usernameError").innerHTML = "You must enter a username";
return false;
}
if(document.loginform.password.value == ""){
document.getElementById("passwordError").innerHTML = "You must enter a password";
return false;
}
}
document.getElementById("loginform").onsubmit = handleinput;
}
</script>
I've been working on this assignment for the longest while. My form validations weren't working previously but then I found out what the error was & everything was working perfectly.
Later on, I had made some changes to the code then deleted those changes and now the validations aren't working again & I can't seem to find what the problem is this time.
Below is my unfinished code:
function validateEmail() {
var email = document.getElementById('email').value;
if( email==null || email=="")
{
alert("Please input an email address");
}
}
function validateFName() {
var firstname = document.getElementById('firstname').value;
if( firstname==null || firstname=="")
{
alert("Please input a last name");
return false;
}
}
function validateLName() {
var lastname = document.getElementById('lastname').value;
if( lastname==null || lastname=="")
{
alert("Please input a last name");
}
}
function validateGender() {
var gender = document.getElementById('gender').value;
if( gender==null || gender=="")
{
alert("Please select a gender");
}
}
function validateDate() {
var date = document.getElementById('date').value;
if( date==null || date=="")
{
alert("Please select a date");
}
}
function validateVName() {
var vname = document.getElementById('vname').value;
if( vname==null || vname=="")
{
alert("Please input a victim's name");
}
}
function validateVEmail() {
var vemail = document.getElementById('vemail').value;
if( vemail==null || vemail=="")
{
alert("Please input a victim's email");
}
}
<div id="navi">
<nav>
<ul class="fancyNav">
<li id="home">Home</li>
<li id="news">TRUTH</li>
<li id="about">DARE</li>
</ul>
</nav>
</div>
<div id="box">
<form id="truth">
<h1> Truth </h1>
<label> First Name: </label> <input type="text" name="firstname" id="firstname" maxlength="30" placeholder="John" /> <br><br>
<label> Last Name: </label> <input type="text" name="lastname" id="lastname" maxlength="30" placeholder="Doe" /> <br><br>
<label> Email:</label> <input type="text" name="email" id="email" /> <br><br>
<label> Male </label><input type="radio" name="gender" id="gender" value="male"/>
<label> Female </label><input type="radio" name="gender" id="gender" value="female"/> <br><br>
<label> Date to be performed: </label><input type="date" name="date" id="date" /><br><br>
<h2> Victim </h2>
<label> Name: </label> <input type="text" name="vname" id="vname" maxlength="30" /><br><br>
<label> Email:</label> <input type="text" name="vemail" id="vemail" /> <br><br>
<h2> Please select a truth questions below </h2> <br>
<input type="radio" name="truth" value="q1"> Have you ever fallen and landed on your head? <br>
<input type="radio" name="truth" value="q2"> Have you ever return too much change? <br>
<input type="radio" name="truth" value="q3"> Have you ever been admitted into the hospital? <br>
<input type="radio" name="truth" value="q4"> Have you ever baked a cake? <br>
<input type="radio" name="truth" value="q5"> Have you ever cheated on test? <br>
<input type="radio" name="truth" value="q6"> Did you ever wish you were never born? <br>
<input type="radio" name="truth" value="q7"> Did you ever hide from Sunday School? <br><br>
<input type="submit" onclick="validateFName(); validateLName(); validateGender(); validateDate(); validateVName(); validateVEmail();" /> <br>
</form>
</div>
<input type="submit" onclick="validateFName(); validateLName(); validateGender(); v
typo in function name, onclick="validateFName()...
it should be validateLName()
and you define duplicate
<!DOCTYPE html>
<html> // remove this one
The best possible solution would be to not use any alert boxes at all but instead embed the error message next to the place of the error, but that would be more involved. Instead, to stick with this solution, first add an id to your submit button:
<button type="submit" id="truth-submit">Submit</button>
Then, attach an onclick handler through JavaScript (and rewrite your code to be more re-usable):
// Only run when the window fully loads
window.addEventListener("load", function() {
function validateEmail() {
var email = document.getElementById("email").value;
if (email === null || email === "") {
return "Please input an email address";
}
return "";
}
function validateFName() {
var firstname = document.getElementById("firstname").value;
if (firstname === null || firstname === "") {
return "Please input an first name";
}
return "";
}
function validateLName() {
var lastname = document.getElementById("lastname").value;
if (lastname === null || lastname === "") {
return "Please input an last name";
}
return "";
}
function validateGender() {
var gender = document.getElementById("gender").value;
if (gender === null || gender === "") {
return "Please select a gender";
}
return "";
}
function validateDate() {
var date = document.getElementById("date").value;
if (date === null || date === "") {
return "Please select a date";
}
return "";
}
function validateVName() {
var vname = document.getElementById("vname").value;
if (vname === null || vname === "") {
return "Please input a victim's name";
}
return "";
}
function validateVEmail() {
var vemail = document.getElementById("vemail").value;
if (vemail === null || vemail === "") {
return "Please input a victim's email";
}
return "";
}
document.getElementById("truth-submit").addEventListener("click", function(event) {
// Grab all of the validation messages
var validationMessages = [validateFName(), validateLName(),
validateGender(), validateDate(), validateVName(), validateVEmail()];
var error = false;
// Print out the non-blank ones
validationMessages.forEach(function(message) {
if (message) {
alert(message);
error = true;
}
});
// Stop submission of the form if an error occurred
if (error) {
event.preventDefault();
}
}, false);
}, false);