How to replace the error message in form validation - javascript

I've tried a form validation using jquery.validate.min.js.
Error message will display on empty fields while clicking submit button.
And my problem is. I don't want that error message. Have to show red border of every empty field. Can't get idea about that.
thanks in advance
jQuery(".contact_form").validate({
rules: {
fname: {
required: true,
},
lname: {
required: true,
},
location: {
required: true,
},
phone: {
required: true,
},
mail: {
required: true,
mail: true
},
subjct: {
required: true,
},
message: {
required: true,
},
},
submitHandler: function (form) {
var postData = $(form).serializeArray();
var result = {};
$.each(postData, function () {
result[this.name] = this.value;
});
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<form class="contact_form" method="post">
<div class="row">
<input type="text" class="f_name" name="fname" placeholder="First Name *">
<input type="text" class="l_name" name="lname" placeholder="Last Name">
</div>
<div class="row">
<input type="number" class="phone_number" name="phone" placeholder="Phone Number *">
<input type="email" class="mail_val" name="mail" placeholder="Email ID">
</div>
<div class="row">
<input type="text" placeholder="Subject *" name="subjct" class="subjct_content">
<textarea class="form_textarea" name="message" placeholder="Message *"></textarea>
<input type="submit" value="Submit">
</div>
</form>

To mark red to empty box you can add following to your validate function:
invalidHandler: function(form, validator) {
$('form input,textarea').each(function(){
if($(this).val() == ""){
$(this).css('border', '1px solid red');
}
});
},
errorPlacement: function(){
return false; // suppresses error message text
}

Try following
jQuery(".contact_form").validate({
rules: {
fname: {
required: true,
},
lname: {
required: true,
},
location: {
required: true,
},
phone: {
required: true,
},
mail: {
required: true,
mail: true
},
subjct: {
required: true,
},
message: {
required: true,
},
},
submitHandler: function (form) {
var postData = $(form).serializeArray();
var result = {};
$.each(postData, function () {
result[this.name] = this.value;
});
return false;
},
errorPlacement: function(error,element) {
return true;
}
});
OR you can simply set the error label/span to following style
display:none

Related

Form validation rules changing dynamically

var mandatory = {
emailAddressTextBox: {
required: true,
email: true
},
passwordTextBox: {
required: true,
minlength: 6,
maxlength: 24,
}
};
var nonmandatory = {
nameTextBox: {
required: true,
maxlength: 50
},
loginEmailAddressTextBox: {
required: true,
email: true
},
loginPasswordTextBox: {
required: true,
minlength: 6,
maxlength: 24,
},
loginPasswordAgainTextBox: {
required: true,
minlength: 6,
maxlength: 24,
equalTo: "#loginPasswordTextBox"
}
};
$("#myForm").validate({
rules: ($("input[name='country']").val() === "US") ? mandatory : nonmandatory;
});
I want to change the form validations rules in ajax dynamically based on the country name.
Let's say if it is the UK:
only email and password should be mandatory.
or if it is the US:
along with email, First name and last name should be mandatory.
I am new to Ajax.
Can anyone help me?
Thanks in Advance!
try this answer... in validation rules instead of required:true you have to use this function
required: function(element) {
if ($("#country option:selected").val()== '1') {
return false;
}
else {
return true;
}
}
$(document).ready(function () {
$("#form").validate({
rules: {
"name": {
required: function(element) {
if ($("#country option:selected").val()== '1') {
return false;
}
else {
return true;
}
},
minlength: 5
},
"email": {
required: function(element) {
if ($("#country option:selected").val()== '1') {
return true;
}
else {
return true;
}
},
email: true
},
"password": {
required: function(element) {
if ($("#country option:selected").val()== '1') {
return true;
}
else {
return true;
}
},
email: true
}
},
messages: {
"name": {
required: "Please, enter a name"
},
"email": {
required: "Please, enter an email",
email: "Email is invalid"
},
"password": {
required: "Please, enter password"
}
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
});
body {
padding: 20px;
}
label {
display: block;
}
input.error {
border: 1px solid red;
}
label.error {
font-weight: normal;
color: red;
}
button {
display: block;
margin-top: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js"></script>
<form id="form" method="post" action="#">
<select id="country">
<option value="1">US</option>
<option value="2">UK</option>
</select>
<label for="name">Name</label>
<input type="text" name="name" id="name" />
<label for="email">Email</label>
<input type="email" name="email" id="email" />
<label for="name">Password</label>
<input type="text" name="password" id="password" />
<button type="submit">Submit</button>
</form>

How to add my server side PHP code to this form wizard?

I have developed a simple 3 step form wizard for registration.
All the client side validation (JavaScript) is working.
The problem is when a user gets to the last stage and click submit, it does nothing.
I want it to direct to the PHP code I have written.
Update The next button does nothing when I click on it after updating my html code
Updated HTML code
<form action="register.php">
<div id ="personal-form">
<h4><b>Personal Details:</b></h4>
<hr>
<div class="form-group">
<label class="sr-only" for="first-name">First name</label>
First Name
<input type="text" name="firstname" placeholder="" class="form-control" id="firstname">
</div>
<div class="form-group">
Last Name
<label class="sr-only" for="last-name">Last name</label>
<input type="text" name="lastname" placeholder="" class="form-control" id="lastname">
</div>
<div class="form-group">
Phone Number
<label class="sr-only" for="name">Phone Number</label>
<input type="text" name="phone" placeholder="" class="form-control" id="phone">
</div>
<div class="form-group">
<p class="has-error" id="error-msg"></p>
</div>
<div class="f1-buttons">
<button type="button" id="first-next" class="btn btn-next">Next</button>
</div>
</div>
<div id="store-form">
........
<button type="button" class="btn btn-previous" id="first-
previous">Previous</button>
<button type="button" class="btn btn-next"
id="second-next">Next</button></center>
</div>
<div id="account-form">
........
<button type="button" class="btn btn-previous" id="second-
previous">Previous</button>
<button type="submit" class="btn btn-next" id="submit">Submit</button>
</center>
</div>
</form>
JavaScript code
function init() {
//hide the other two forms
$("#store-form").hide();
$("#account-form").hide();
//$("#first-next").addClass("disabled");
//var state2 = $("#state").val();
/*$("#state").change(function ()
{
var state2 = $("#state").val();
alert(state2);
})*/
//alert(state2);
$.validator.setDefaults({
errorClass: 'help-block',
highlight: function (element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function (element) {
$(element).closest('.form-group').removeClass('has-error');
}
})
$.validator.addMethod('strongPassword', function (value, element) {
return this.optional(element) || value.length >= 6
// && /\d/.test(value) && /[a-z]/i.test(value);
}, 'Your password must be at least 6 characters long');//'Your password must be at least 6 characters long, contain at least on e number and a character');
//The method for all select options
$.validator.addMethod('checkSelect', function (value, element) {
return this.optional(element) || (value != "Please choose...")
// && /\d/.test(value) && /[a-z]/i.test(value);
}, 'You must select an option');//'Your password must be at least 6 characters long, contain at least on e number and a character');
$("#personal-form").validate({
rules: {
firstname: {
required: true,
nowhitespace: true,
lettersonly: true
},
lastname: {
required: true,
nowhitespace: true,
lettersonly: true
},
phone: {
required: true,
}
},
messages: {
firstname: {
required: 'Please enter your first name',
nowhitespace: 'Please enter a valid first name',
lettersonly: 'Please enter only alphabets'
},
lastname: {
required: 'Please enter your first name',
nowhitespace: 'Please enter a valid last name',
lettersonly: 'Please enter only alphabets'
},
phone: {
required: "Please enter a valid phone no"
}
}
});
/*if($("#personal-form").valid() == true)
{
$("#first-next").removeClass("disabled");
alert($("#personal-form").valid());
}*/
if ($("#first-next").click(function () {
if ($("#personal-form").valid() == true) {
//$("#first-next").removeClass("disabled");
//alert($("#personal-form").valid());
$("#personal-form").hide();
$("#store-form").fadeIn();
$("#account-form").hide();
//$("#error-msg").html("");
}
else {
//$("#error-msg").html("Please correct all errors before clicking next");
}
}));
/*$("#firstname").on('change', function() {
if($("#firstname").valid() == true)
{
console.log("test");
alert("It worked");
}
});*/
//$('#firstname').on('input', function()
//{
//var firstname = $("#firstname").val();
//alert(firstname);
//alert("hello");
//console.log("test");
//alert("You just typed something in the firstname field");
//});
$("#store-form").validate({
rules: {
storename: {
required: true
},
state: {
required: true,
checkSelect: true
},
lga: {
required: true,
checkSelect: true
},
address: {
required: true,
},
category: {
required: true,
checkSelect: true
},
description: {
required: true,
lettersonly: true
}
},
messages: {
storename: {
required: "Please enter the name of your store"
},
address: {
required: "Please enter the address of your store"
},
description: {
required: "Briefly descibe what you sell or do"
}
}
});
if ($("#second-next").click(function () {
if ($("#store-form").valid() == true) {
//$("#first-next").removeClass("disabled");
//alert($("#personal-form").valid());
$("#personal-form").hide();
$("#store-form").hide();
$("#account-form").fadeIn();
//$("#error-msg").html("");
}
else {
//$("#error-msg").html("Please correct all errors before clicking next");
}
}));
if ($("#first-previous").click(function () {
$("#personal-form").fadeIn();
$("#store-form").hide();
$("#account-form").hide();
//$("#error-msg").html("");
}));
$("#account-form").validate({
rules: {
email: {
required: true,
email: true
},
password: {
required: true,
strongPassword: true
},
password2: {
required: true,
equalTo: "#password"
}
},
messages: {
email: {
required: 'Please enter your email address',
email: "Please enter a valid email address"
},
password: {
required: 'Please enter your password',
strongPassword: "Your password is not strong enough"
},
password2: {
required: 'Please enter your password',
equalTo: "Both passwords don't match"
}
}
});
$("#email").on('input', function () {
if ($("#email").valid() == true) {
//console.log("test");
//alert("It worked");
var email = $("#email").val();
$("#check-email-server").load('php/check_email.php', { "email": email });
}
});
$("#email").on('focusout', function () {
if ($("#email").valid() == true) {
//console.log("test");
//alert("It worked");
var email = $("#email").val();
$("#check-email-server").load('php/check_email.php', { "email": email });
}
});
if ($("#second-previous").click(function () {
$("#personal-form").hide();
$("#store-form").fadeIn();
$("#account-form").hide();
//$("#error-msg").html("");
}));
}
The three forms should all connect to 1 PHP file.
The problem is when I click submit it does nothing.
How do I connect the three different forms together and make the submit button work?
The last button should be of type "submit" <button type="submit"> otherwise a normal "button" doesn't submit the form (or maybe you have to write a js click event to submit the form.)
AND
You must put all inputs in the same form to send them to php, consider to replace forms with divs and wrap them inside an unique form. If you use 3 different forms only the input elements of the last form will be sent to backend but I think you need all inputs.
This is an example:
http://jsfiddle.net/2sdtjydu/1/
<form action="" method="post">
<div id ="personal-form">
<h4><b>Personal Details:</b></h4>
<hr>
<div class="form-group">
<label class="sr-only" for="first-name">First name</label>
First Name
<input type="text" name="firstname" placeholder="" class="form-control" id="firstname">
</div>
<div class="form-group">
Last Name
<label class="sr-only" for="last-name">Last name</label>
<input type="text" name="lastname" placeholder="" class="form-control" id="lastname">
</div>
<div class="form-group">
Phone Number
<label class="sr-only" for="name">Phone Number</label>
<input type="text" name="phone" placeholder="" class="form-control" id="phone">
</div>
<div class="form-group">
<p class="has-error" id="error-msg"></p>
</div>
<div class="f1-buttons">
<button type="button" id="first-next" class="btn btn-next">Next</button>
</div>
</div>
<div id="store-form">
........
<button type="button" class="btn btn-previous" id="first-
previous">Previous</button>
<button type="button" class="btn btn-next"
id="second-next">Next</button>
</div>
<div id="account-form">
........
<button type="button" class="btn btn-previous" id="second-
previous">Previous</button>
<button type="submit" class="btn btn-next" id="submit">Submit</button>
</div>
</form>
And this is the jquery:
$(document).ready(function () {
//hide the other two forms
$("#store-form").hide();
$("#account-form").hide();
//$("#first-next").addClass("disabled");
//var state2 = $("#state").val();
/*$("#state").change(function ()
{
var state2 = $("#state").val();
alert(state2);
})*/
//alert(state2);
$.validator.setDefaults({
errorClass: 'help-block',
highlight: function (element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function (element) {
$(element).closest('.form-group').removeClass('has-error');
}
})
$.validator.addMethod('strongPassword', function (value, element) {
return this.optional(element) || value.length >= 6
// && /\d/.test(value) && /[a-z]/i.test(value);
}, 'Your password must be at least 6 characters long');//'Your password must be at least 6 characters long, contain at least on e number and a character');
//The method for all select options
$.validator.addMethod('checkSelect', function (value, element) {
return this.optional(element) || (value != "Please choose...")
// && /\d/.test(value) && /[a-z]/i.test(value);
}, 'You must select an option');//'Your password must be at least 6 characters long, contain at least on e number and a character');
$("form").validate({
rules: {
firstname: {
required: true,
nowhitespace: true,
lettersonly: true
},
lastname: {
required: true,
nowhitespace: true,
lettersonly: true
},
phone: {
required: true,
},
storename: {
required: true
},
state: {
required: true,
checkSelect: true
},
lga: {
required: true,
checkSelect: true
},
address: {
required: true,
},
category: {
required: true,
checkSelect: true
},
description: {
required: true,
lettersonly: true
},
email: {
required: true,
email: true
},
password: {
required: true,
strongPassword: true
},
password2: {
required: true,
equalTo: "#password"
}
},
messages: {
firstname: {
required: 'Please enter your first name',
nowhitespace: 'Please enter a valid first name',
lettersonly: 'Please enter only alphabets'
},
lastname: {
required: 'Please enter your first name',
nowhitespace: 'Please enter a valid last name',
lettersonly: 'Please enter only alphabets'
},
phone: {
required: "Please enter a valid phone no"
},
storename: {
required: "Please enter the name of your store"
},
address: {
required: "Please enter the address of your store"
},
description: {
required: "Briefly descibe what you sell or do"
},
email: {
required: 'Please enter your email address',
email: "Please enter a valid email address"
},
password: {
required: 'Please enter your password',
strongPassword: "Your password is not strong enough"
},
password2: {
required: 'Please enter your password',
equalTo: "Both passwords don't match"
}
}
});
/*if($("#personal-form").valid() == true)
{
$("#first-next").removeClass("disabled");
alert($("#personal-form").valid());
}*/
if ($("#first-next").click(function () {
if ($("#personal-form :input").valid() == true) {
//$("#first-next").removeClass("disabled");
//alert($("#personal-form").valid());
$("#personal-form").hide();
$("#store-form").fadeIn();
$("#account-form").hide();
//$("#error-msg").html("");
}
else {
//$("#error-msg").html("Please correct all errors before clicking next");
}
}));
/*$("#firstname").on('change', function() {
if($("#firstname").valid() == true)
{
console.log("test");
alert("It worked");
}
});*/
//$('#firstname').on('input', function()
//{
//var firstname = $("#firstname").val();
//alert(firstname);
//alert("hello");
//console.log("test");
//alert("You just typed something in the firstname field");
//});
if ($("#second-next").click(function () {
if ($("#store-form :input").valid() == true) {
//$("#first-next").removeClass("disabled");
//alert($("#personal-form").valid());
$("#personal-form").hide();
$("#store-form").hide();
$("#account-form").fadeIn();
//$("#error-msg").html("");
}
else {
//$("#error-msg").html("Please correct all errors before clicking next");
}
}));
if ($("#first-previous").click(function () {
$("#personal-form").fadeIn();
$("#store-form").hide();
$("#account-form").hide();
//$("#error-msg").html("");
}));
$("#email").on('input', function () {
if ($("#email").valid() == true) {
//console.log("test");
//alert("It worked");
var email = $("#email").val();
$("#check-email-server").load('php/check_email.php', { "email": email });
}
});
$("#email").on('focusout', function () {
if ($("#email").valid() == true) {
//console.log("test");
//alert("It worked");
var email = $("#email").val();
$("#check-email-server").load('php/check_email.php', { "email": email });
}
});
if ($("#second-previous").click(function () {
$("#personal-form").hide();
$("#store-form").fadeIn();
$("#account-form").hide();
//$("#error-msg").html("");
}));
});

minlength input field validation - JQuery

I have the JQuery validations below that just ensure that something is written within the input fields, I also have maxlength in the html.
However, I was hoping someone could shed some light on the situation and inform me on how I can add some type of minlength to the jquery code below so I don't require to do any additional functions?
$('#form1').submit(function (e) {
e.preventDefault();
}).validate({
rules: {
txtusername: {
required: true
},
txtfirstname: {
required: true
},
txtemail: {
required: true
},
txtpassword: {
required: true
},
passwordconfirm: {
required: true
}
},
messages: {
txtusername: {
required: "Please enter your Username."
},
txtfirstname: {
required: "Please enter your First Name."
},
txtemail: {
required: "Please enter your Email."
},
txtpassword: {
required: "Please enter your Password."
},
passwordconfirm: {
required: "Please enter your password again."
}
},
errorPlacement: function (error, element) {
error.appendTo(element.parent().prev());
},
submitHandler: function (form, user) {
CheckUser(form);
return false;
}
});
Example HTML -
<div data-role="fieldcontainer">
<label for="txtusername" data-theme="d">Username:</label>
<input type="text" id="txtusername" name="txtusername" maxlength="12" placeholder="Enter Username"/>
</div>
You can use like below:
rules:{
txtusername: {
required: true,
minlength: 3
},
}

jQuery validation not working with that form

I have been trying to validate a form with jquery validate plugin.As a newbie i am facing problem with that.Here is the code
$(document).ready(function() {
$("#log-form").validate({
errorElement: 'div',
rules: {
"username": {
required: true,
minlength: 5
},
"password": {
required: true,
minlength: 5
}
},
messages: {
username: {
required: "Provide a username,sire",
minlength: "Username with length 5 atleast,is required"
},
password: {
required: "Provide a password,sire",
minlength: "Minimum length of 5 is required for password,sire"
}
}
submitHandler: function(form) {
form.submit();
}
});
});
<form name="log-form" id="log-form" method="post" action="check_login.php">
<label for="username">Username</label>
<input type="text" class="" id="username" name="username">
<br>
<label for="password">Password</label>
<input type="password" class="" id="password" name="password">
<br>
<button type="submit" name="sub-btn" class="sub-btn">Login</button>>
</form>
The validation is not working as i change field after typing in one neither on submiting the form.
As per #unidentified: There is a syntax error in your code, missing , after the messages property. Please check How can I debug my JavaScript code?
$(document).ready(function() {
$("#log-form").validate({
errorElement: 'div',
rules: {
"username": {
required: true,
minlength: 5
},
"password": {
required: true,
minlength: 5
}
},
messages: {
username: {
required: "Provide a username,sire",
minlength: "Username with length 5 atleast,is required"
},
password: {
required: "Provide a password,sire",
minlength: "Minimum length of 5 is required for password,sire"
}
}, // syntax error, comma was missing here
submitHandler: function(form) {
form.submit();
}
});
});

Validation success control

Here is my code. My main problem is that var validationbool triggers success even if only one field of contact form is valid and it does not care if the other ones are invalid. How can I create better control that var validationbool = true only when all elements are valid.
$(document).ready(function () {
var validationBool = false;
$('#register-form').validate({
rules: {
name: {
minlength: 3,
required: true
},
email: {
required: true,
email: true
},
phone: {
required: true,
minlength: 10
},
country: {
required: true
},
boat: {
required: true
},
lat: {
required: true
},
registration: {
required: true
},
file: {
required: true
}
},
highlight: function (element) {
$(element).closest('.control-group').removeClass('success').addClass('error');
validationBool = false;
},
success: function (element) {
element.text('').addClass('valid').closest('.control-group').removeClass('error').addClass('success');
validationBool = true;
}
});
$('#register-form').on('submit', function(e){
e.preventDefault();
if(validationBool){
var theData = {
name: $('#name').val(),
phone: $('#phone').val(),
email: $('#email').val(),
country: $('#country').val(),
lat: $('#lat').val(),
lng: $('#lng').val(),
boat: $('#boat').val(),
registration: $('#registration').val(),
file: $('#file').val()
};
$.ajax({ // ajax call starts
url: "functions/enroll.php",
type: 'post',
data: theData,
success: function(data)
{
swal("Your request has been recieved!", "We will contact you for confirmation soon", "success");
document.getElementById('name').value='',
document.getElementById('phone').value='',
document.getElementById('email').value='',
document.getElementById('country').value='',
document.getElementById('lat').value='',
document.getElementById('lng').value='',
document.getElementById('boat').value='',
document.getElementById('file').value='',
document.getElementById('registration').value='';
}
});
}
});
});
I would use the .valid() mehthod.
This would be printed like
var myForm = $("#register-form");
myForm.validate();
then, instead of using the "validationBool" variable, use
if (myForm.valid())
to check if the form is validated - this will check all fields.
Here is what I thought will work for you with validate():
[Note: This is just an example I used and you can use the similar approach - You don't have to explicitly use any boolean variable for knowing whether you can submit.
Do note, I used:
Invalidate Handler - Callback for custom code when an invalid form is submitted. Called with an event object as the first argument, and the validator as the second.
Submit Handler - Callback for handling the actual submit when the form is valid. Gets the form as the only argument. Replaces the default submit. The right place to submit a form via Ajax after it is validated.
Html code:
<form class="cmxform" id="commentForm" method="get" action="http://www.google.com">
<fieldset>
<legend>Please provide your name, email address (won't be published) and a comment</legend>
<p>
<label for="cname">Name (required, at least 2 characters)</label>
<input id="cname" name="name" minlength="2" type="text" />
</p>
<p>
<label for="cemail">E-Mail (required)</label>
<input id="cemail" type="email" name="email" />
</p>
<p>
<label for="curl">URL (optional)</label>
<input id="curl" type="url" name="url" />
</p>
<p>
<label for="ccomment">Your comment (required)</label>
<textarea id="ccomment" name="comment"></textarea>
</p>
<p>
<input class="submit" type="submit" value="Submit" />
</p>
</fieldset>
</form>
JS code:
$("#commentForm").validate({
rules: {
name: {
minlength: 3,
required: true
},
email: {
required: true,
email: true
},
phone: {
required: true,
minlength: 10
},
country: {
required: true
},
boat: {
required: true
},
lat: {
required: true
},
registration: {
required: true
},
file: {
required: true
}
},
invalidHandler: function (event, validator) {
var errors = validator.numberOfInvalids();
/*Here you will get your errors
if (errors) {
var message = errors == 1
? 'You missed 1 field. It has been highlighted'
: 'You missed ' + errors + ' fields. They have been highlighted';
$("div.error span").html(message);
$("div.error").show();
} else {
$("div.error").hide();
}*/
alert(errors);
},
submitHandler: function (element) {
//Handler for submit action
//$(form).ajaxSubmit();
alert("submit");
}
});
JSFiddle Link here

Categories