How would i validate this form with jquery? - javascript

This is my html
<div><center><b class="cust_heading">ONLINE FREIGHT QUOTES</b><br>
Instant prices with multiple carriers</center>
</div>
<div class="field_heading"><b>Shipment type* </b><span id="shipmentError" class="cust_error"></span></div>
<div class="fiftyPercent">
<input type="radio" name="shipment" value="export"> Export
</div>
<div class="fiftyPercent">
<input type="radio" name="shipment" value="import"> Import
</div>
<div class="field_heading"><b>Load type* </b><span id="loadError" class="cust_error"></span></div>
<div class="fiftyPercent">
<input type="radio" name="load" value="fcl"> FCL
</div>
<div class="fiftyPercent">
<input type="radio" name="load" value="lcl"> LCL
</div>
<div style="display:none; width:100%;" id="weight_volume_row">
<div class="fiftyPercent">
Weight (kg)*<span id="lcl_weightError" class="cust_error"></span><br><input type="text" name="lcl_weight" id="lcl_weight" value="" placeholder="e.g 100" style=" width:70%;">
</div>
<div class="fiftyPercent">
Volume (m<sup>3</sup>)*<span id="lcl_volumeError" class="cust_error"></span><br><input type="text" name="lcl_volume" id="lcl_volume" placeholder="e.g 1" value="" style=" width:70%;">
</div>
</div>
<div class="field_heading"><b id="cust_include_text">Include pickup* </b><span id="pickupError" class="cust_error"></span></div>
<div class="fiftyPercent">
<input type="radio" name="pickup" value="yes"> Yes
</div>
<div class="fiftyPercent">
<input type="radio" name="pickup" value="no"> No
</div>
<div class="field_heading"><b id="cust_zipcode_text">Pickup zip code* </b></div>
<div style="width:100%;">
<input id="pickupZipCode" placeholder="Enter a city or zip code" title="pickupZipCode" type="text" class="ui-autocomplete-input" autocomplete="off" role="textbox" aria-autocomplete="list" style=" width:85%;"><input type="hidden" name="postal_hid_data" id="postal_hid_data" value="">
<select name="choosePort" id="choosePort" style=" width:85%; display:none;"><option disabled="disabled" selected="selected" value="">Choose a port</option><option value="test1">test1</option><option value="test2">test2</option><option value="test3">test3</option></select>
<select name="choosePortOther" id="choosePortOther" style=" width:85%; display:none;"><option value="">Choose a port</option><option value="test4">test4</option><option value="test5">test5</option><option value="test6">test6</option></select>
<span id="zipError" class="cust_error"></span>
</div>
<div class="field_heading"><b id="cust_dest_text">Port of destination* </b></div>
<div style="width:100%;padding:5px 0px;">
<input id="destPort" placeholder="Enter a port or country" title="portDestination" type="text" class="ui-autocomplete-input" autocomplete="off" role="textbox" aria-autocomplete="list" style=" width:85%;"><input type="hidden" name="des_hid_data" id="des_hid_data" value="">
<span id="desError" class="cust_error"></span>
</div>
<div style="width:90%; float:left;padding:5px 0px;">
<input class="searchButton orange-bttn cust_btn" id="cust_form_submit" name="cust_form_submit" type="submit" value="Buscar Naviera" style="float:right;">
</div>
</div>
and my jquery validate form is lookin like this, what is it im doing wrong. Using the wrong form id?
$(function() {
$('cust_main_box').validate({
rules: {
pickupZipCodeUS: {
required: true
},
destPortUS: {
required: true
},
//lcl_weightForm2US: {
//required: true
//},
//lcl_volumeForm2US: {
//required: true
//},
},
messages: {
pickupZipCodeUS: {
required: 'Please enter a valid zip-code',
},
destPortUS: {
required: 'Please enter a valid port',
},
//lcl_weightForm2US: {
//required: 'Please enter a valid weight',
//},
//lcl_volumeForm2US: {
//required: 'Please enter a valid volume',
//},
}
)};
});
The code that was commented out had to do with another form within the jquery, I'd like to include it whenever i figure out what it is i'm doing wrong.

as #undefined already told you, proably the element should be .cust_main_box or #cust_main_box, but the problem in your code is validate closing:
)};
should be
});
So your correct JS:
$(function() {
$('#cust_main_box').validate({
rules: {
pickupZipCodeUS: {
required: true
},
destPortUS: {
required: true
}
//,lcl_weightForm2US: {
//required: true
//},
//lcl_volumeForm2US: {
//required: true
//},
},
messages: {
pickupZipCodeUS: {
required: 'Please enter a valid zip-code'
},
destPortUS: {
required: 'Please enter a valid port'
}
//,lcl_weightForm2US: {
//required: 'Please enter a valid weight',
//},
//lcl_volumeForm2US: {
//required: 'Please enter a valid volume',
//},
}
});
});

Your major problems:
1) The jQuery Validate plugin requires that all input elements to be validated must have name attributes. Those name attributes must also be where your declared rules are assigned.
<input type="text" name="pickupZipCodeUS" ...
<input type="text" name="destPortUS" ...
2) You are missing a form element. The jQuery Validate plugin can only work when the user input elements are contained within a set of <form></form> tags.
3) $('cust_main_box') is not a valid selector in this context. Give the new <form> element an id="cust_main_box" and change the selector to $('#cust_main_box').
<form id="cust_main_box" ...
4) The closing braces for your .validate() call are reversed. They should be this: }).
$('#cust_main_box').validate({
// rules & options
}); // <-- this here
Working Code:
$(function () {
$('#cust_main_box').validate({
rules: {
pickupZipCodeUS: { // <-- this is the field name
required: true
},
destPortUS: { // <-- this is the field name
required: true
}
},
messages: {
pickupZipCodeUS: {
required: 'Please enter a valid zip-code',
},
destPortUS: {
required: 'Please enter a valid port',
}
}
});
});
Working DEMO: http://jsfiddle.net/fTwsG/
You're using a bunch of invalid and deprecated markup, so you should also put your HTML through the W3C HTML Validation tool.

Related

Jquery Validation plug-in dependency from Radio buttons not working

I need some inputs to be required only if certain options are checked in another input (radio). In short, if Type 1 documents is chosen, I need type 1 field number to be obligatory. It's easier to visualize through this jsfiddle below:
https://jsfiddle.net/kbhatd51/2/
Could you please help me? Thanks in advance
<form id="registerform" method="post">
<div class="form-group">
<label >Type of Document</label><br>
<input type="radio" class="radioForm" id="fis" name="tipop" value="0" > <label for="fis"> Type 1</label><br>
<input type="radio" class="radioForm" id="jur" name="tipop" value="1" > <label for="jur"> Type 2</label><br>
</div>
<label for="tipop"> Number</label>
<div class="form-group">
<fieldset id="cpf1">
<label for=cpf1>Type 1 No.:</label>
<input type="number" class="form-control" placeholder="000.000.000-00" name="cpf" id="cpf" >
</fieldset>
<fieldset id="cnpj1">
<label for=cnpj1> Type 2 No.:
<input type="number" class="form-control" placeholder=" 00.000.000/0001-00" name="cnpj" id="cnpj"></label>
</fieldset>
</div>
<input name="submit" type="submit" value="Submit!">
</form>
JS validate:
$("#registerform").validate({
rules: {
cpf: {
required: "#fis:checked"
},
cnpj: {
required: "#jur:checked"
}
}
});
The required method needs to return true for the field to be required.
So you can simply pass a function to required which will check if the radio element is checked
required method
required( dependency-callback )
Type: Function()
The function is executed with the element as it's only argument: If it returns true, the element is required.
$("#registerform").validate({
debug: true,
rules: {
cpf: {
required: function(elem) {
return $('#fis').is(":checked")
}
},
cnpj: {
required: function(elem) {
return $('#jur').is(":checked")
}
}
}
});
Check out the -- JSFiddle Example -- here.

jquery validation with php form

I am trying to use jquery validation for a php form to change your password but I keep getting the error "Your password must be the same as above" when the password is correct. I can't seem to find out where I have went wrong at all... Here's the JS code
var changepassword = function() {
return {
init: function() {
/*
* Jquery Validation, https://github.com/jzaefferer/jquery-validation
*/
$('#changepassword').validate({
errorClass: 'help-block animation-slideUp',
errorElement: 'div',
errorPlacement: function(error, e) {
e.parents('.form-group > div').append(error);
},
highlight: function(e) {
$(e).closest('.form-group').removeClass('has-success has-error').addClass('has-error');
$(e).closest('.help-block').remove();
},
success: function(e) {
if (e.closest('.form-group').find('.help-block').length === 2) {
e.closest('.help-block').remove();
} else {
e.closest('.form-group').removeClass('has-success has-error');
e.closest('.help-block').remove();
}
},
rules: {
'newpassword': {
required: true,
minlength: 6
},
'newpassword-verify': {
equalTo: '#newpassword',
required: true
}
},
messages: {
'newpassword': {
required: 'Please provide a password',
minlength: 'Your password must be at least 6 characters long'
},
'newpassword-verify': {
required: 'Please provide a password',
minlength: 'Your password must be at least 6 characters long',
equalTo: 'Please enter the same password as above'
}
}
});
}
};
}();
This is the PHP/HTML for the form
<form method="POST" class="form-horizontal form-bordered" id="changepassword">
<div class="form-group">
<label class="col-md-3 control-label" for="newpassword">New Password</label>
<div class="col-md-6">
<input type="password" id="newpassword" name="newpassword" class="form-control" placeholder="New Password" required>
</div>
</div>
<!-- This is where I keep getting the error -->
<div class="form-group">
<label class="col-md-3 control-label">Repeat Password</label>
<div class="col-md-6">
<input type="password" id="newpassword-verify" name="newpassword-verify" class="form-control" placeholder="Repeat Password" required>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="oldpassword">Current Password</label>
<div class="col-md-6">
<input type="password" id="oldpassword" name="oldpassword" class="form-control" placeholder="Password" required>
</div>
</div>
<div class="form-group form-actions">
<button type="submit" name="update" class="btn btn-block btn-primary">Update</button>
</div>
</form>
Sorry, I was able to fix it by making a new file called settings1.php then removing the old one and renaming the new one with the old name.

jQuery Validate not validating on form submit

I'm facing some problems with jQuery Validate. I've already put the rules but when i'm submitting the form, nothing happens.
I'm using ASP.NET MVC 4 and Visual Studio 2010.
EDIT: Click here to see my entire code. I'm trying to post it here but i'm getting the following error: 403 Forbidden: IPS signature match. Below is part of my code with Andrei Dvoynos's suggestion. I'm getting the same error. Clicking on submit and the page being reloaded
#{
ViewBag.Title = "Index";
}
#section Teste1{
<script type="text/javascript">
$(document).ready(function () {
$("#moeda").maskMoney();
$("#percent").maskMoney();
$(":input").inputmask();
$('#tel').focusout(function () {
var phone, element;
element = $(this);
element.unmask();
phone = element.val().replace(/\D/g, '');
if (phone.length > 10) {
element.inputmask({ "mask": "(99) 99999-999[9]" });
} else {
element.inputmask({ "mask": "(99) 9999-9999[9]" });
}
}).trigger('focusout');
//the code suggested by Andrei Dvoynos, i've tried but it's occurring the same.
$("#form1").validate({
rules: {
cpf: { required: true, },
cep: { required: true, },
tel: { required: true, },
email: { required: true, },
cnpj: { required: true, },
},
highlight: function (element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function (element) {
$(element).closest('.form-group').removeClass('has-error');
},
errorElement: 'span',
errorClass: 'help-block'
});
});
</script>
}
#using (#Html.BeginForm("", "", FormMethod.Post,
new { id = "form1", name = "form1" }))
{
<fieldset>
<legend>Sign In</legend>
<div class="form-group" id="divCpf">
<label for="cpf">CPF</label>
<input data-inputmask="'mask': '999.999.999-99'" class="form-control" id="cpf" />
</div>
<div class="form-group" id="divCep">
<label for="cep">CEP</label>
<input data-inputmask="'mask' : '99999-999'" type="text" class="form-control" id="cep" placeholder="CEP" />
</div>
<div class="form-group" id="divTel">
<label for="tel">Telefone</label>
<input type="text" class="form-control" id="tel" placeholder="tel" />
</div>
<div class="form-group" id="email">
<label for="email">Email</label>
<input type="text" class="form-control" id="email" placeholder="Email" />
</div>
<div class="form-group" id="divcnpj">
<label for="cnpj">CNPJ</label>
<input data-inputmask="'mask' : '99.999.999/9999-99'" type="text" class="form-control" id="cnpj" placeholder="CNPJ" />
</div>
<div class="form-group">
<label for="moeda">Moeda</label>
<input type="text" id="moeda" data-allow-zero="true" class="form-control" />
</div>
<div class="form-group">
<label for="Percent">Percent</label>
<input type="text" id="percent" data-suffix="%" data-allow-zero="true" class="form-control" maxlength="7" />
</div>
<input type="submit" class="btn btn-default" value="Sign In" id="sign" />
</fieldset>
}
My tests (all unsuccessful):
1 - put the $("form").validate() into $(document).ready()
2 - put the required class on the fields.
jQuery Validate plugin version: 1.13.0
In addition to the fatal problem you fixed thanks to #Andrei, you also have one more fatal flaw. The name attribute is missing from your inputs.
Every element must contain a unique name attribute. This is a requirement of the plugin because it's how it keeps track of every input.
The name is the target for declaring rules inside of the rules option.
$("#form1").validate({
rules: { // <- all rule declarations must be contained within 'rules' option
cpf: { // <- this is the NAME attribute
required: true,
....
DEMO: http://jsfiddle.net/3tLzh/
You're missing the rules property when calling the validate function, try something like this:
$("#form1").validate({
rules: {
cpf: { required: true, },
cep: { required: true, },
tel: { required: true, },
email: { required: true, },
cnpj: { required: true, },
},
highlight: function (element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function (element) {
$(element).closest('.form-group').removeClass('has-error');
},
errorElement: 'span',
errorClass: 'help-block'
});

Conditional validation with BootstrapValidator

I'm using BootstrapValidator plugin to validate a form, however i have following problem. I have a "Phone" field and a "Mobile" field if the user does not enter either of them, I wanted to launch a custom message (you need to inform one phone number), and if he inform any (phone or mobile) validation would be satisfied.
The doubt is: Is it possible to use conditional inside BootstrapValidator?
This seems to be working for a lot of people derived from this post:
$('form').validate({
rules: {
Phone: {
required: true
},
Mobile: {
required: true
}
},
highlight: function(element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function(element) {
$(element).closest('.form-group').removeClass('has-error');
},
errorElement: 'span',
errorClass: 'help-block',
errorPlacement: function(error, element) {
if(element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
}
});
and the html:
<form>
<div class="form-group">
<label class="control-label" for="Phone">Phone:</label>
<div class="input-group">
<input class="form-control" name="Phone" type="text" />
</div>
</div>
<div class="form-group">
<label class="control-label" for="Mobile">Mobile:</label>
<div class="input-group">
<input class="form-control" name="Mobile" type="text" />
</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>

bug in jquery validation

I have used the jquery form validation from this site http://jquery.bassistance.de/validate/demo/. In this site validation works when the field values are empty. I need it to work if i set values to the form fields for example the value for the email field is Email Address. How can i modify that?. The internal script that i have used is
<script type="text/javascript">
$.validator.setDefaults({
submitHandler: function() { alert("submitted!"); }
});
$().ready(function() {
// validate the comment form when it is submitted
$("#commentForm").validate();
// validate signup form on keyup and submit
$("#signupForm").validate({
rules: {
firstname: "required",
lastname: "required",
username: {
required: true,
minlength: 2
},
password: {
required: true,
minlength: 5
},
confirm_password: {
required: true,
minlength: 5,
equalTo: "#password"
},
email: {
required: true,
email: true
},
topic: {
required: "#newsletter:checked",
minlength: 2
},
agree: "required"
},
messages: {
firstname: "Please enter your firstname",
lastname: "Please enter your lastname",
username: {
required: "Please enter a username",
minlength: "Your username must consist of at least 2 characters"
},
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
confirm_password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long",
equalTo: "Please enter the same password as above"
},
email: "Please enter a valid email address",
agree: "Please accept our policy"
}
});
// propose username by combining first- and lastname
$("#username").focus(function() {
var firstname = $("#firstname").val();
var lastname = $("#lastname").val();
if(firstname && lastname && !this.value) {
this.value = firstname + "." + lastname;
}
});
//code to hide topic selection, disable for demo
var newsletter = $("#newsletter");
// newsletter topics are optional, hide at first
var inital = newsletter.is(":checked");
var topics = $("#newsletter_topics")[inital ? "removeClass" : "addClass"]("gray");
var topicInputs = topics.find("input").attr("disabled", !inital);
// show when newsletter is checked
newsletter.click(function() {
topics[this.checked ? "removeClass" : "addClass"]("gray");
topicInputs.attr("disabled", !this.checked);
});
});
</script>
This is my html
<form class="cmxform" id="signupForm" method="get" action="">
<fieldset>
<legend>Validating a complete form</legend>
<p>
<label for="firstname">Firstname</label>
<input id="firstname" name="firstname" />
</p>
<p>
<label for="lastname">Lastname</label>
<input id="lastname" name="lastname" />
</p>
<p>
<label for="username">Username</label>
<input id="username" name="username" />
</p>
<p>
<label for="password">Password</label>
<input id="password" name="password" type="password" />
</p>
<p>
<label for="confirm_password">Confirm password</label>
<input id="confirm_password" name="confirm_password" type="password" />
</p>
<p>
<label for="email">Email</label>
<input id="email" name="email" type="email" />
</p>
<p>
<label for="agree">Please agree to our policy</label>
<input type="checkbox" class="checkbox" id="agree" name="agree" />
</p>
<p>
<label for="newsletter">I'd like to receive the newsletter</label>
<input type="checkbox" class="checkbox" id="newsletter" name="newsletter" />
</p>
<fieldset id="newsletter_topics">
<legend>Topics (select at least two) - note: would be hidden when newsletter isn't selected, but is visible here for the demo</legend>
<label for="topic_marketflash">
<input type="checkbox" id="topic_marketflash" value="marketflash" name="topic" />
Marketflash
</label>
<label for="topic_fuzz">
<input type="checkbox" id="topic_fuzz" value="fuzz" name="topic" />
Latest fuzz
</label>
<label for="topic_digester">
<input type="checkbox" id="topic_digester" value="digester" name="topic" />
Mailing list digester
</label>
<label for="topic" class="error">Please select at least two topics you'd like to receive.</label>
</fieldset>
<p>
<input class="submit" type="submit" value="Submit"/>
</p>
</fieldset>
</form>
So my understanding from your question is that if they leave the field with the default value, e.g. "Email Address", you want that to error. You'll need to create your own custom validation method, using the addMethod function. Then you refer to that method in your options. I think something like this is the correct syntax:
$.validator.addMethod("checkdefault", function (value, element, params) {
if (params[0] == params[1] || params[0].length === 0) {
// user hasn't changed value from the default, or they've left it completely blank
return false;
} else {
return true;
}
});
email: {
// pass an array of params, first one is the field value, second is your default text
checkdefault: [$("#email").val(), 'Email Address'],
email: true
}
When you have set you values, call $("#signupForm").validate() if you set your values from javascript. If you do it with server side technology validate on document.Ready()

Categories

Resources