Validation on the hidden fields on knockoutJS - javascript

I am trying perform validation on the fields entered on the KnockoutJS, the issue is validation in the hidden fields. The page is like this
When the Has Customer Account Number? field is selected I want the Billing address is same as Shipping Address and Billing Address should be invisible. So the Email And First Name need to be required in that scenario. I want to the fields to be required only when then both fields are unchecked, even if one is checked then no validation should be fired on the Billing Address section.
<div class="col-md-6" data-bind="visible: !sameAsShippingAddress() && !hasCustomerAccNum()">
<h4>Billing Address:</h4>
<div class="form-group required">
<label for="EmailCompetitor_Billing" class="control-label">Email:</label>
<input type="email" maxlength="150" id="EmailCompetitor_Billing" name="EmailCompetitor_Billing" class="form-control" data-bind="value: emailCompetitor_Billing" required />
</div>
<div class="form-group required">
<label for="FirstNameCompetitor_Billing" class="control-label">First Name:</label>
<input type="text" maxlength="150" id="FirstNameCompetitor_Billing" name="FirstNameCompetitor_Billing" class="form-control" data-bind="value: firstNameCompetitor_Billing" required />
</div>
And the JS is like
self.emailCompetitor_Billing = ko.observable().extend({ required: { params: true, message: "Required! Please enter a valid email" }, email: { params: true, message: "Required! Please enter a valid email" } });
self.firstNameCompetitor_Billing = ko.observable().extend({ required: { params: true, message: "Required! Please First Name " } });
I tried to set the onlyIf like below in the required section atleast hoping it will fire the validation rules only when the Has Customer Account Number is unchecked but no luck
self.firstNameCompetitor_Billing = ko.observable().extend({ required: { params: true, message: "Required! Please First Name ", onlyIf: !self.hasCustomerAccNum } });
I am very newto this KnockoutJS world any help is greatly appreciated
Update I tried to make the required
self.sameAsShippingAddress = ko.observable(false);
self.hasCustomerAccNum = ko.observable(false);
.......
self.sameAsShippingAddress = ko.observable().extend({ required: false });
self.hasCustomerAccNum = ko.observable().extend({ required: false });
.......
self.firstNameCompetitor_Billing = ko.observable().extend({ required: { params: true, message: "Required! Please First Name ", onlyIf: !self.hasCustomerAccNum() } });
It throws error on page load knockout.validation.min.js:10 Uncaught TypeError: r.condition is not a function

you can add data-validation attribute in data-bind like this.
data-bind="attr: { 'data-validation':isVisible?'required':false}"

Related

jQuery validation plugin is validating only specific form fields

I am trying basic client-side form validation using jQuery validation plugin.I have a basic sign up form, if I click on a button to create an account with all fields empty(just for testing), I am getting nice error messages as expected on all form fields except for only one field for inputting cellphone number. I have downloaded the code from the internet and this is the only field I have added.I am using Xampp, Things became even more strange after I moved all files to another computer and try to test the same validation, Guess what? it's no longer working as expected for all fields. This problem has been frying my brains, any help I will be grateful below is the code
HTML
<h2 class="form-signin-heading">Sign Up</h2><hr />
<div id="error">
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="Username" name="user_name" id="user_name" />
</div>
<div class="form-group">
<input type="email" class="form-control" placeholder="Email address" name="user_email" id="user_email" />
<span id="check-e"></span>
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="Cellphone" name="user_cellphone" id="user_cellphone" />
</div>
<div class="form-group">
<input type="password" class="form-control" placeholder="Password" name="password" id="password" />
</div>
<div class="form-group">
<input type="password" class="form-control" placeholder="Retype Password" name="cpassword" id="cpassword" />
</div>
<hr />
<div class="form-group">
<button type="submit" class="btn btn-default" name="btn-save" id="btn-submit">
<span class="glyphicon glyphicon-log-in"></span> Create Account
</button>
</div>
</form>
JS
$('document').ready(function()
{
/* validation */
$("#register-form").validate({
rules:
{
user_name: {
required: true,
minlength: 3
},
user_cellphone: {
required: true,
number: true
},
password: {
required: true,
minlength: 8,
maxlength: 15
},
cpassword: {
required: true,
equalTo: '#password'
},
user_email: {
required: true,
email: true
}
},
messages:
{
user_name: "Enter a Valid Username",
user_cellphone:{
required: "Provide a phone number",
number: "Phone Needs To Be a number"
},
password:{
required: "Provide a Password",
minlength: "Password Needs To Be Minimum of 8 Characters"
},
user_email: "Enter a Valid Email",
cpassword:{
required: "Retype Your Password",
equalTo: "Password Mismatch! Retype"
}
},
submitHandler: submitForm
});
/* validation */
/* form submit */
function submitForm()
{
var data = $("#register-form").serialize();
$.ajax({
type : 'POST',
url : 'register.php',
data : data,
beforeSend: function()
{
$("#error").fadeOut();
$("#btn-submit").html('<span class="glyphicon glyphicon-transfer"></span> sending ...');
},
success : function(data)
{
if(data==1){
$("#error").fadeIn(1000, function(){
$("#error").html('<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span> Sorry email already taken !</div>');
$("#btn-submit").html('<span class="glyphicon glyphicon-log-in"></span> Create Account');
});
}
else if(data=="registered")
{
$("#btn-submit").html('Signing Up');
setTimeout('$(".form-signin").fadeOut(500, function(){ $(".signin-form").load("successreg.php"); }); ',5000);
}
else{
$("#error").fadeIn(1000, function(){
$("#error").html('<div class="alert alert-danger"><span class="glyphicon glyphicon-info-sign"></span> '+data+' !</div>');
$("#btn-submit").html('<span class="glyphicon glyphicon-log-in"></span> Create Account');
});
}
}
});
return false;
}
/* form submit */
Below is a snapshot of the form, I cant really figure out where is the problem.
You're declaring the number rule, but your corresponding message is assigned to the minlength rule...
rules: {
user_cellphone: {
required: true,
number: true
},
....
},
messages: {
user_cellphone: {
required: "Provide a phone number",
minlength: "Phone Needs To Be a number"
},
....
And document should not be in quotes...
$(document).ready(function() {...
Working DEMO: http://jsfiddle.net/bh5g0wfe/
Side note: You may want to read this too...
Dangerous implications of Allman style in JavaScript

JS validation doesn't run after I enter a valid input and submit the form with rest of the input fields empty

I am developing a web directory with a form on one of its pages. JS validation plug in is used. While submitting the form without filling any Input fields, the form throws errors below each input field as expected! But submitting the form with just one input box filled in refreshes the current page as the action value is set to current page with PHP codes in it, instead of staying on the same page to continue to throw errors for the rest of the fields that are yet to be filled in! I have searched online to find nothing useful in figuring out what is wrong with the script. Could anyone here please look into the code below and recommend the best solution? Thanks.
$(document).ready(function() {
$("#userForm").validate({
rules: {
cname: {
required: true,
lettersonly: true,
minlength: 3
},
cemail: {
required: true,
email: true
},
cphone: {
required: true,
number: true,
minlength: 10,
maxlength: 10
},
cbusiness: {
required: true,
url: true
},
cbcategory: {
required: true,
minlength: 6
},
curl: {
required: true,
minlength: 6
},
},
messages: {
cname: "Please enter your name",
cemail: "Please enter a valid email address",
cphone: {
required: "Please enter your phone number",
number: "Please enter only numeric value"
},
cbusiness: {
required: "Please enter your business",
},
cbcategory: {
required: "Please enter a business category",
},
curl: {
required: "Please enter the URL to your website",
},
}
});
});
The form is as below.
<form action="" method="post" name="userForm" id="userForm">
<input type="text" name="cname" id="cname" placeholder=" Your Name">
<input type="text" name="cemail" id="cemail" class="email" placeholder="Your Email">
<input type="text" name="cphone" id="cphone" placeholder="Your Phone">
<input type="text" name="cbusiness" id="cbusiness" class="email" placeholder=" Your Business">
<input type="text" name="cbcategory" id="cbcategory" placeholder="Business category">
<input type="text" name="curl" id="curl" class="email" placeholder="URL"><br>
<label for='message'>Enter the code in the box below : </label>
<img src="captcha.php?rand=<?php echo rand();?>" id='captchaimg'>
<input type="text" id="captcha_code" name="captcha_code">
<input type="submit" name="Submit" id="Submit" value="Submit" class="button1"><br>
Can't read the image? click <a href='javascript: refreshCaptcha();'>here</a> to refresh.
</form>
Assuming you have included the validation libraries corectly, you will have to set messages for all of the validation types like:
messages: {
cname: {
required: "Please enter your name",
lettersonly: "Letters only",
minlength: "Min length 3 required"
},
cemail: {
required: "Please enter a valid email address",
email: "Invalid email"
}
}
Working JSFIDDLE.
You have to include the plugin files something like this:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/additional-methods.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.js"></script>
UPDATE:
After discussing with OP on chat, we came to the conclusion that the plugin files had to be included correctly and there was an incompatibility between the jQuery version(v 1.7.1) he used and the plugin version(v 1.16.0). So we had to add a custom method for lettersonly.
The code for custom method:
jQuery.validator.addMethod("lettersonly", function(value, element) {
return this.optional(element) || /^[a-z]+$/i.test(value);
}, "Letters only please");

Enable stripe button upon bootstrap validation

I wanted to use BootstrapValidator to validate couple of fields and enable stripe button upon validation. The problem is that the button is enabled once any of the fields are validated. I am trying to enabled the stripe button once both fields are validated.(ignore the datepicker field). below is my javascript code.
$('#myform')
.bootstrapValidator({
message: 'This value is not valid',
//live: 'submitted',
icon: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
fname: {
message: 'The first name is not valid',
validators: {
notEmpty: {
message: 'The first name is required and can\'t be empty'
},
stringLength: {
min: 2,
max: 30,
message: 'The first name must be more than 6 and less than 30 characters long'
},
/*remote: {
url: 'remote.php',
message: 'The username is not available'
},*/
regexp: {
regexp: /^[a-zA-Z]+$/,
message: 'The first name can only consist of alphabetical letters'
}
}
},
lname: {
message: 'The last name is not valid',
validators: {
notEmpty: {
message: 'The last name is required and can\'t be empty'
},
stringLength: {
min: 3,
max: 30,
message: 'The last name must be more than 6 and less than 30 characters long'
},
/*remote: {
url: 'remote.php',
message: 'The username is not available'
},*/
regexp: {
regexp: /^[a-zA-Z]+$/,
message: 'The last name can only consist of alphabetical letters'
}
}
},
}
})
.on('success.form.fv', function(e) {
// Prevent submit form
e.preventDefault();
var $form = $(e.target),
validator = $form.data('bootstrapValidator');
$form.find('#result').html('Thanks for signing up. Now you can sign in as ' + validator.getFieldElements('fname').val()).show();
});
$('.stripe-button-el').attr("disabled", true );
});
And this is the form:
<form id="myform" method="post" class="form-horizontal">
<div class="form-group" >
<label class="col-sm-3 control-label">Full name</label>
<div class="col-sm-4">
<input type="text" class="form-control" name="fname" placeholder="First name" id="fname" />
</div>
<div class="col-sm-4">
<input type="text" class="form-control" name="lname" placeholder="Last name" id="lname" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Pick a Date</label>
<div class="col-sm-4">
<input class="form-control" name="date" type="text" id="datepicker"/>
</div>
<div class="col-sm-4">
<script src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="<?php echo $stripe['publishable_key']; ?>"
data-amount="5000" data-zip-code = "true" data-description="Whatever">
</script>
</div>
</div>
<div class="form-group" >
<label class="col-sm-4 control-label" id='results'></label>
</div>
</form>
You need an event triggered with every keystroke to determine whether the form is valid. Once you know its valid, you can take action on the button. BootstrapValidator's API includes everything you need to do this (other than capturing the event itself).
You can append this on method to your $('#myform') chain:
.on('keyup', function() {
// Get your form's validator
var validator = $('#myform').data('bootstrapValidator');
// Validate the form
validator.validate();
// Check if the form is valid
if (validator.isValid()) {
// Perform action on Stripe button
}
});

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

jquery confirm password validation

I am using jquery for form validation. Rest is well except the confirm password field. Even when the same password is typed, the Please enter the same password. is not removed.
My script is:
<script type="text/javascript">
$(document).ready(function() {
$("#form1").validate({
rules: {
password: {
required: true, minlength: 5
},
c_password: {
required: true, equalTo: "#password", minlength: 5
},
email: {
required: true, email: true
},
phone: {
required: true, number: true, minlength: 7
},
url: {
url: true
},
description: {
required: true
},
gender: {
required: true
}
},
messages: {
description: "Please enter a short description.",
gender: "Please select your gender."
}
});
});
-->
</script>
And inside the form tag:
<div class="form-row"><span class="label">Password</span><input type="password" name="password" class="required" id="password" /></div>
<div class="form-row"><span class="label">Confirm Password</span><input type="password" name="c_password" id="c_password" /></div>
Any suggestion?
Would be much thankful for the help.
Your fields doesn't have the ID property.
In jQuery the "#password" selector means "the object that has an id property with value 'password'"
Your code should look like this:
<input type="password" name="password" id="password" class="required"/>
<input type="password" id="password" class="nomal required error" value="" name="cpassword">
<input type="password" equalto="#password" class="nomal required error" value="" name="cpassword">
Be sure that your password's input text has id 'password'
rules: {
isn't closed. Put another } after:
messages: {
description: "Please enter a short description.",
gender: "Please select yor gender."
}
This is as well as the answer about the element ID's.
Be sure that no other input with tag id='password' in that same page.
I came across some issues when using camelCase id's for the password inputs. I finnally got it working with different 'name' and 'id'.
<input type="password" id="pass" placeholder="New password" name="newPassword">
<input type="password" id="pass2" placeholder="New password" name="repeatNewPassword">
<input type="email" id="inputNewEmail" name="newEmail" placeholder="New email">
<input type="email" id="repeatNewEmail" name="repeatNewEmail" placeholder="New email>
Then in the JS:
rules: {
newPassword: {
minlength: 6
},
repeatNewPassword: {
minlength: 6,
equalTo: "#pass"
},
newEmail: { email: true},
repeatNewEmail: {email: true, equalTo: '#inputNewEmail'},
}
So refer to the input field by its 'name' but define equalTo deppendency using 'id'. I'm not sure about the camelCase issue, for the email inputs it worked, but exactly same nomenclature with password inputs didn't work, according to my experience
if($("#newpassword").val()!== ($("#conformpassword").val())){
$('#newpasswordId').html('<font color="red">Your password does not match</font>');
$("#newpassword").val('');
$("#conformpassword").val('');
$('#newpassword').css("border", "#FF0000 solid 1px")
$('#conformpassword').css("border", "#FF0000 solid 1px")
$("#newpassword").focus();
return false;
}

Categories

Resources