Form validation rules changing dynamically - javascript

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>

Related

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("");
}));
});

How to replace the error message in form validation

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

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();
}
});
});

jquery validate when field not empty

I validate my form using jquery validate like this:
$("#formuser").validate({
rules: {
accountname: {
required: true,
minlength: 6
},
T1: {
required: true,
minlength: 6
},
accountpassword1: {
required: true,
minlength: 8
},
accountpassword2: {
required: true,
minlength: 8,
equalTo: "#accountpassword1"
},
},
});
HTML:
<input id="accountpassword1" class="text-input form-control" type="text" name="accountpassword1" size="24" placeholder="password" >
<input class="text-input form-control" type="text" name="accountpassword2" size="24" placeholder="password" >
this worked for me But. I need to check jquery validate when password1 and password 2 not empty. my mean is if password input is empty jquery validate not validate field else validate field password1 and password2.
how do create this?
NOTE:: i need to only check validate accountpassword1 and accountpassword1 with this method.
You can use the depends option like
function isPasswordPresent() {
return $('#accountpassword1').val().length > 0;
}
$("#formuser").validate({
rules: {
accountname: {
required: true,
minlength: 6
},
T1: {
required: true,
minlength: 6
},
accountpassword1: {
//required: true is not required
minlength: {
depends: isPasswordPresent,
param: 8
}
},
accountpassword2: {
required: isPasswordPresent,
minlength: {
depends: isPasswordPresent,
param: 8
},
equalTo: {
depends: isPasswordPresent,
param: "#accountpassword1"
}
},
},
});
Demo: Fiddle
I had the same requirement So I used this code
$.validator.addMethod(
"regex",
function(value, element, regexp){
return this.optional(element) || regexp.test(value);
},
"Please check your input.");
$('#registration').validate({
rules: {
first_name: {
required: true , regex: /([-a-zA-Z0-9]|\0)/
},
last_name: {
required: true , regex: /([-a-zA-Z0-9]|\0)/
}
},
errorPlacement: function(){
return false;
},
submitHandler: function (form){
alert('sucess')
return false;
}
});
its working for me. Hope it helps

Categories