Jquery validator addmethod minor issue - javascript

im new to jquery validator, im trying to use regex to check if numbers, capital and special characters are included. I have the following html
<div class="wrapper wrapper-content animated fadeInRight">
<div class="row white-bg spacepad">
<div id="keypass">
<form method="POST" class="form-horizontal" id="keyform" name="keypasser">
<div class="form-group"><label class="col-sm-2 control-label">Decryption Key For EPins</label>
<div class="col-sm-10"><input type="text" required="required" class="form-control" name="keypassx" /></div>
</div>
<div class="form-group"><label class="col-sm-2 control-label">Confirm Decryption Key</label>
<div class="col-sm-10"><input type="text" required="required" class="form-control" name="keypass2" /></div>
</div>
<input type="submit" class="btn btn-primary btn-rounded btn-block" value="Submit" />
</form>
</div>
</div>
and the following jquery, when i remove the addmethod it works, please what am i doing wrong
<script type="text/javascript">
$(function() {
// Initialize form validation on the registration form.
// It has the name attribute "registration"
$("form[name='keypasser']").validate({
// Specify validation rules
rules: {
keypassx: {
required: true,
minlength: 8,
passchecker: true,
},
keypass2: {
required: true,
equalTo: "#keypassx",
}
},
// Specify validation error messages
messages: {
keypassx: {
required: "Epins password required",
minlength: "Minimum length allowed is 8 characters",
passchecker: "Password should contain numbers, special characters and one uppercase",
},
keypass2: {
required: "Confirmation password requied",
equalTo: "Password does not match Epins Password",
}
},
$.validator.addMethod("passchecker",
function(value, element) {
return /^[A-Za-z0-9\d=!\-#._*]*$/.test(value);
});
// Make sure the form is submitted to the destination defined
// in the "action" attribute of the form when valid
submitHandler: function(form) {
form.submit();
}
});
});
</script>
kindly help out

Please try to use regular expression as
var patt = new RegExp("e");
var res = patt.test(str);
You directly use the regular expression. Please create object and try it.

The addMethod function accepts three params check the docs:
$.validator.addMethod("passchecker",
function(value, element) {
if(/^[A-Za-z0-9\d=!\-#._*]*$/.test(value)) {
return true;
} else {
return false;
}
}, "Your validation message goes here");

Related

Validation on the hidden fields on knockoutJS

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}"

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

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 valid and error class to form

i'm using jquery validate plugin. I have this form:
<form id="form-test" class="form-inline" role="form">
<div id="test" class="form-group has-feedback">
<label class="control-label" for="inputSuccess4">Input with success</label>
<input type="text" name="prova" id="prova" class="form-control" id="inputSuccess4">
<span class="glyphicon glyphicon-ok form-control-feedback"></span>
</div>
</form>
and this is my jquery validate file:
$('#form-test').validate({
rules: {
prova: {
required: true,
minlength: 4,
maxlength: 7
}
},
submitHandler: function(form) {
form.submit();
}
});
If input is valid I need to add to div (with id test) class has-success and if is not valid has-error. How can I do this? thank you
$('#form-test').validate({
errorClass: "has-error",
validClass: "has-success",
rules: {
prova: {
required: true,
minlength: 4,
maxlength: 7
}
},
submitHandler: function(form) {
form.submit();
}
});
Just create an if condition if it is .valid():
isValid = $('#form-test').valid();
if (isValid) {
$('#test').addClass('has-success');
} else {
$('#test').addClass('has-error');
}

Simple jquery validation - custom position error message placement

I am using jquery validate plugin to validate number in a form , how can i place the returned error message under the input button , i am unable to achieve,
Here is my image with the issue and what i need,pls check - http://i.imgur.com/Gt5aNxs.png
Please suggest me how to put the error message in a custom Div under the button instead of default underneath.
Here is my code:
<section id="contact" class="content">
<div class="container">
<h2>Contact Form Demo</h2>
<div class="row">
<div class="span12 contact-form">
<form action="mail.php" method="POST" class="form-horizontal contact-form" id="contact-form">
<!--<?php $formKey->outputKey(); ?> -->
<fieldset>
<div class="control-group">
<label class="control-label" for="inputPhone">Phone</label>
<div class="controls">
<input class="input-80" name="phone" type="text" id="inputPhone" placeholder="inc. country & area code">
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" value="Send" class="btn" id="btn-place">Send!</button>
</div>
<div >place here</div>
</div>
</fieldset>
</form>
</div>
</div>
</div>
</section>
<!-- javascript -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="js/jquery.validate.min.js"></script>
<script>
// contact form validation
$(document).ready(function(){
$('#contact-form').validate(
{
rules: {
name: {
minlength: 3,
required: true
},
email: {
required: true,
email: true
},
phone: {
minlength: 11,
required: false,
number: true
},
subject: {
minlength: 3,
required: true
},
message: {
minlength: 20,
required: true
}
},
highlight: function(label) {
$(label).closest('.control-group').addClass('error');
},
success: function(label) {
label
.text('OK!').addClass('valid')
.closest('.control-group').addClass('success');
}
});
// contact form submission, clear fields, return message,script no shown here
</script>
All you need to do is specify the errorLabelContainer in your options and specify the div you want the errors to go into:
$('#contact-form').validate({
//all your other options here
errorLabelContainer: '#errors'
});
Then just make sure you specify that your place here div has the id errors like this:
<div id="errors"></div>
See a working example here: http://jsfiddle.net/ryleyb/aaEFQ/ (note that I also specified the wrapper option, which you'll probably want if there are multiple errors).
errorPlacement: function(error, element) {
if((element.attr('name') === 'color[]')){
error.appendTo("div#errors");
}
else if(element.attr('name') === 'font[]' ){
error.appendTo("#font-error");
}
else{
element.before(error);
}
}

Categories

Resources