I have made landing page and using jquery after() method for showing validation messages. When User click multiple times validation messages getting appended and input boxes getting out of form clicks after clicks. When I use append() over after() it does not shows validation error messages at all. What can I use methods for showing validation messages? or Do I need to do with fixed height width of form or is there is huge mistake I have done? Thanks. Validation error messages
Form
<div class="col-lg-4 col-md-3 col-sm-3 col-xs-12 " id="e_form">
<h2>Enquiry Form</h2>
<form name="enquiry-form" method="post" action="#" id="enquiry-form" novalidate="">
<div class="form-group">
<input type="text" class="form-control input-height" name="name" id="name" placeholder="Enter your name here" required="required">
</div>
<div class="form-group">
<input type="email" class="form-control input-height" name="email" id="email" placeholder="Enter your Email-ID" required="required">
</div>
<div class="form-group">
<input type="text" class="form-control input-height" name="number" id="phone" placeholder=" Enter your Mobile Number" required="required" maxlength="10">
</div>
<div class="form-group">
<input type="text" class="form-control input-height" name="city" id="city" placeholder="Enter your city" required="required">
</div>
<div class="form-group">
<textarea class="form-control" rows="4" name="details" id="details" placeholder="Enter message here" required="required"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default btn-lg" name="Submit" id="submit" onclick="CheckBlank(event)">Get Started</button>
</div>
</form>
</div>
Jquery Validation
<script>
function CheckBlank(e) {
e.preventDefault();
var name = $('#name').val();
var email = $('#email').val();
var phone = $('#phone').val();
var city = $('#city').val();
var details = $('#details').val();
if (name === "" && email === "" && phone === "" && city === "" && details === "") {
// $('input,textarea').css("border", "1px solid red");
$("#name").after("<div class='validation' style='color:red;'>Please Enter Your Name</div>");
$("#email").after("<div class='validation' style='color:red;'>Please Enter Your Email ID</div>");
$("#phone").after("<div class='validation' style='color:red;'>Please Enter Your Phone Number</div>");
$("#city").after("<div class='validation' style='color:red;'>Please Enter Your City</div>");
$("#details").after("<div class='validation' style='color:red;'>Please Enter Your Message</div>");
// $("#submit").prop("disabled",true);
}
else if (name === "" || email === "" || phone === "" || city === "" || details === "") {
$("#submit").prop('disabled',false);
$('#name').val() !== '' ? $('#name').css("border", "none") && $('.validation').remove() :
$("#name").after("<div class='validation' style='color:red;'>Please Enter Your Name</div>");
$('#email').val() !== '' && !ValidateEmail($("#email").val()) ? $('#email').css("border", "none") && $('.validation').remove() :
$("#email").after("<div class='validation' style='color:red;'>Please Enter Your Email ID</div>");
$('#phone').val() !== '' ? $('#phone').css("border", "none") && $('.validation').remove() && $('.valid-email').remove():
$("#phone").after("<div class='validation' style='color:red;'>Please Enter Your Phone Number</div>");
$('#city').val() !== '' ? $('#city').css("border", "none") && $('.validation').remove() :
$("#city").after("<div class='validation' style='color:red;'>Please Enter Your city</div>");
$('#details').val() !== '' ? $('#details').css("border", "none") && $('.validation').remove() :
$("#details").after("<div class='validation' style='color:red;'>Please Enter Your Message</div>");
}
else {
$("#submit").after("<div class='greeting' style='color:#3b9a80;'>Thank You !! We Will Contact You Within 24 Hours !!</div>");
$('input,textarea').val("");
$("#submit").prop('disabled',false);
$('.validation').remove();
$(".greeting").fadeOut(5000);
}
}
$("#name,#email,#phone,#city,#details").on("keydown", function(e) {
if (e.which == 9) { // tab key press
$('#name').val() !== '' ? $('#name').css("border", "none") && $('.validation').remove() :
$("#name").after("<div class='validation' style='color:red;'>Please Enter Your Name</div>");
$('#email').val() !== '' && !ValidateEmail($("#email").val()) ? $('#email').css("border", "none") && $('.validation').remove() && $('.valid-email').remove():
$("#email").after("<div class='validation' style='color:red;'>Please Enter Your Email ID</div>");
$('#phone').val() !== '' ? $('#phone').css("border", "none") && $('.validation').remove() && $('.valid-phone').remove():
$("#phone").after("<div class='validation' style='color:red;'>Please Enter Your Phone Number</div>");
$('#city').val() !== '' ? $('#city').css("border", "none") && $('.validation').remove() :
$("#city").after("<div class='validation' style='color:red;'>Please Enter Your city</div>");
$('#details').val() !== '' ? $('#details').css("border", "none") && $('.validation').remove() :
$("#details").after("<div class='validation' style='color:red;'>Please Enter Your Message</div>");
}
});
$("#name,#city").on("keypress", function(e) {
var regex = /^[a-zA-Z ]*$/; // prevent pressing numbers and other symbols
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
return true;
} else {
e.preventDefault();
return false;
}
});
$("#phone").on("change", function(e) {
if ($("#phone").val().length != 10) {
$("#phone").append("<div class='valid-phone' style='color:red;'>Please Enter Valid Phone Number</div>");
}
else{
$('.valid-phone').remove();
}
});
$('#phone').keypress(function(key) {
if (key.charCode < 48 || key.charCode > 57) return false; // prevent pressing other than numbers
});
function ValidateEmail(email) {
var expr = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
return expr.test(email);
}
$("#email").on("change", function() {
if (!ValidateEmail($("#email").val())) {
$('.validation').remove();
$("#email").append("<div class='valid-email' style='color:red;'>Please Enter Valid Email ID</div>");
} else {
$('.valid-email').remove();
return;
}
});
$("#phone,#email,#phone,#city").on({
keydown: function(e) {
if (e.which === 32) // prevent pressing space bar
return false;
},
change: function() {
this.value = this.value.replace(/\s/g, "");
}
});
</script>
If you want to continue with this procedure, it is pretty hard to handle, when you go with increasing form size. I would suggest you to add span elements of error message container with form input and handle the content alone with validation.
<form id="loginform" name="loginform" action="myurl.com" method="post">
<input type="text" name="username" /><span id="usernameError"></span>
<input type="password" name="password" /><span id="passwordError"></span>
<input type="submit" value="Submit" /></form>
And js code will be like
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;}}
This span will act as a container of error messages and we can have better control over error messages with the help of JavaScript
Just add $('div.validation').remove(); in the CheckBlank(e) method
JSFiddle : https://jsfiddle.net/44Luvysr/11/
Related
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>
<!DOCTYPE html>
<html>
<body>
<div class="needContent">
<label for="Password">Password</label>
<span class="red-star">∗</span>
<input type="password" name="Password" id="Password" required="required" onkeyup="starShow()" pattern="^(?=.*\[a-z\])(?=.*\[A-Z\])(?=.*\d)\[a-zA-Z\d\]{8,}$" onchange="check()">
</div>
<div class="needContent">
<label for="Retype_Password">Retype Password</label>
<span class="red-star">∗</span>
<input type="password" name="Retype_Password" id="Retype_Password" pattern="^(?=.*\[a-z\])(?=.*\[A-Z\])(?=.*\d)\[a-zA-Z\d\]{8,}$" required="required" onkeyup="starShow()" onchange="check()">
<p id="status"></p>
<div id="phoneNumber" class="needContent">
<label for="Phone_Number" >Phone Number</label>
<span class="red-star">∗</span>
<input type="tel" name="Phone_Number" id="Phone_Number"
required="required" onchange="Error()" placeholder="999-999-9999"
onkeyup="starShow()" >
<p id="showEorror"></p>
</div>
</div>
<script>
function Error() {
var phn = document.getElementById("Phone_Number").value;
if(phn[3]!="-" && phn[7] != "-" ) {
document.getElementById("showEorror").innerHTML="<span>X</span> The area code of phone number 999-999-9999 can't be all zeros.";
}else if(phn[0] == 0 || phn[1] == 0 && phn[2] == 0){
document.getElementById("showEorror").innerHTML="<span>X</span> The area code of phone number 999-999-9999 can't be all zeros.";
} else {
document.getElementById("showEorrr").style.display = "none";
}
}
function check() {
var pass1 = document.getElementById("Password").value;
var pass2 = document.getElementById("Retype_Password").value;
if (pass1 != "" && pass2 != "") {
if (pass1 != pass2) {
document.getElementById("status").innerHTML = "<span>X</span> Doesn't Match.";
}
}
}
</script>
</body>
</html>
So I am working on my school project and I am trying to display the error "Doesn't Match" same as the one for the phone but I don't know what I am doing wrong. I have attached a screen shot of my output.
You're not resetting the #status text after the password gets properly entered. Try this instead:
if (pass1 != "" && pass2 != "") {
if (pass1 != pass2) {
document.getElementById("status").innerHTML = "<span>X</span> Doesn't Match.";
} else document.getElementById("status").textContent = 'ok';
}
For the phone section, you have a typo or two: "showEorror" vs "showEorrr", which means that, again, the error text does not go away. I recommend using showError or showPhoneError instead.
<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;
}
}
When I am doing JavaScript alert after that value is been null from the input text. But I want that after the JavaScript alert value should be available in the input text.
Here is my code
<script>
function validateform() {
var email = $('#txt_emailID').val();
if (email == null || email == "") {
alert("Email Should Be Complusory");
return false;
}
var atposition = email.indexOf("#");
var dotposition = email.lastIndexOf(".");
if (atposition < 1 || dotposition < atposition + 2 || dotposition + 2 >= email.length) {
alert("Please enter a valid e-mail address...!!!");
return false;
}
}
</script>
<label for="fname">Name</label>
<input type="text" id="txt_name" name="txt_name" placeholder="Your Name.." />
<label for="lname">EmailID</label>
<input type="text" id="txt_emailID" name="email" placeholder="Your EmailID.." />
<label for="lname">Subject</label>
<input type="text" id="txt_subject" name="txt_subject" placeholder="Your Subject.." />
<input type="submit" id="submit_mail" value="Send" />
<script>
$(function () {
$(document).on("click", "#submit_mail", function () {
if (validateform() == false) {
document.getElementById("txt_name").value = $('#txt_name').val();
document.getElementById("txt_subject").value = $('#txt_subject').val();
}
else {
}
});
});
I don't know where I am getting a problem.
You should prevent default action of submit button which is to submit the form.
Use Event.preventDefault();
function validateform() {
var email = $('#txt_emailID').val();
if (email == null || email == "") {
alert("Email Should Be Complusory");
return false;
}
var atposition = email.indexOf("#");
var dotposition = email.lastIndexOf(".");
if (atposition < 1 || dotposition < atposition + 2 || dotposition + 2 >= email.length) {
alert("Please enter a valid e-mail address...!!!");
return false;
}
}
$(function() {
$(document).on("click", "#submit_mail", function(e) {
if (validateform() == false) {
e.preventDefault();
document.getElementById("txt_name").value = $('#txt_name').val();
document.getElementById("txt_subject").value = $('#txt_subject').val();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="fname">Name</label>
<input type="text" id="txt_name" name="txt_name" placeholder="Your Name.." />
<label for="lname">EmailID</label>
<input type="text" id="txt_emailID" name="email" placeholder="Your EmailID.." />
<label for="lname">Subject</label>
<input type="text" id="txt_subject" name="txt_subject" placeholder="Your Subject.." />
<input type="submit" id="submit_mail" value="Send" />
I am building a web form with validation and when the form is submitted with none of the fields filled in It pops up with the error message but then still goes through. Maybe someone else can see my mistake. Below I added the scripts for both the form and validators.
Thank you in advance!
function validateForm()
{
var x=document.forms["contactform"]["fname"].value;
if (x==null || x=="" || x=="First Name*" )
{
alert("Please Provide your First Name");
return false;
}
var y=document.forms["contactform"]["lname"].value;
if (y==null || y=="" || y=="Last Name*" )
{
alert("Please Provide your Last Name");
return false;
}
var em = document.forms["contactform"]["email"].value;
if (em == null || em == "" || em == "Email*")
{
alert("Please Provide your Email");
return;
}
var atpos=em.indexOf("#");
var dotpos=em.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=em.length)
{
alert("E-mail address is not valid");
return false;
}
var ph = document.forms["contactform"]["phone"].value;
if (ph ==null || ph=="" || ph=="Phone*" )
{
alert("Please Provide your Phone Number");
return;
}
document.contactform.submit();
}
<form class="cmxform" id="contactform" method="post" action="contact-life-factor2.asp" >
<input name="fname" type="text"class="required" onBlur="if(this.value=='')this.value=this.defaultValue;" onFocus="if(this.value===this.defaultValue)this.value='';" value="First Name*" />
<input name="lname" type="text"class="required" onBlur="if(this.value=='')this.value=this.defaultValue;" onFocus="if(this.value===this.defaultValue)this.value='';" value="Last Name*" />
<input name="company" type="text"class="" onBlur="if(this.value=='')this.value=this.defaultValue;" onFocus="if(this.value===this.defaultValue)this.value='';" value="Company" />
<input name="email" type="text" class="required" onBlur="if(this.value=='')this.value=this.defaultValue;" onFocus="if(this.value===this.defaultValue)this.value='';" value="Email*"/>
<input name="phone" type="text" class="" onBlur="if(this.value=='')this.value=this.defaultValue;" onFocus="if(this.value===this.defaultValue)this.value='';" value="Phone*"/><br>
<div class="clearfix"></div>
<div style="padding-left:6px; padding-top:5px; font-weight:bold; color:#686868;">Comments:</div>
<textarea name="comments" cols="" rows="" onBlur="if(this.value=='')this.value=this.defaultValue;" onFocus="if(this.value===this.defaultValue)this.value='';" value="comments" ></textarea>
<input type="submit" value="Submit" name="submit" class="submit" onClick="javascript:validateForm();" style="margin-right:44px;"/>
</form>
So there are a couple of issues:
return; is not equivalent to return false; or return true;, you need to be explicit with your return value as this will dictate whether or not your form submits (true) or not (false).
Remove the onclick from your submit button and move it to your form tag as an onsubmit event
onsubmit="return validateForm()"
onclick of submit validation doesnt stop.use onsubmit in form
<form class="cmxform" id="contactform" method="post" onsubmit="return validateForm();" action="contact-life-factor2.asp" >
function validateForm()
{
var x=document.forms["contactform"]["fname"].value;
if (x==null || x=="" || x=="First Name*" )
{
alert("Please Provide your First Name");
return false;
}
var y=document.forms["contactform"]["lname"].value;
if (y==null || y=="" || y=="Last Name*" )
{
alert("Please Provide your Last Name");
return false;
}
var em = document.forms["contactform"]["email"].value;
if (em == null || em == "" || em == "Email*")
{
alert("Please Provide your Email");
return false;
}
var atpos=em.indexOf("#");
var dotpos=em.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=em.length)
{
alert("E-mail address is not valid");
return false;
}
var ph = document.forms["contactform"]["phone"].value;
if (ph ==null || ph=="" || ph=="Phone*" )
{
alert("Please Provide your Phone Number");
return;
}
}