I've successfully used the definition on other pages before. Basically it should make the field required, but fail if only whitespace is entered (by default typing i.e. a single space causes the required check to pass). I tossed an alert in just to see when the handler is fired as well as the value of this at that time. It's fired when I expect it, and the value is as I expect it. It should be returning false but apparently it isn't because the error isn't being displayed. If I remove that depends function and just have required: true, it correctly displays the error when the user leaves the field. What's going on?
ContactName: {
required: {
depends: function() {
alert("'" + $(this).val() + "'");
if ($.trim($(this).val()).length === 0) {
$(this).val($.trim($(this).val()));
return false;
}
return true;
}
},
maxlength: 100
}
You can change the rule for ContactName like (for details take a look to rules examples):
ContactName: {
required: true,
minlength: {
depends: function(ele) {
if (ele.value.trim().length === 0) {
ele.value = '';
return false;
}
return true;
}
},
maxlength: 100
}
The snippet:
$("#commentForm").validate({
rules: {
ContactName: {
required: true,
minlength: {
depends: function(ele) {
if (ele.value.trim().length === 0) {
ele.value = '';
return false;
}
return true;
}
},
maxlength: 100
}
},
messages: {
ContactName: "Please enter your contact name"
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.min.js"></script>
<form class="cmxform" id="commentForm" method="get" action="">
<fieldset>
<p>
<label for="ContactName">Name</label>
<input id="ContactName" name="ContactName" type="text">
</p>
<p>
<input class="submit" type="submit" value="Submit">
</p>
</fieldset>
</form>
Related
I have a form that requires user to enter their digital signature before signing up. It looks like below:
So prior to signing up, user MUST enter their signature on the canvas box provided. I use jquery validation to validate my other fields before coming to this final page for signature.
I can validate all the fields except for the signature field. Any idea what I can do?
<div class="row">
<div class="col-12 col-md-8 offset-md-2 pl-3 pr-3 pt-2 mb-0">
<canvas class="display-block signature-pad" style="touch-action: none;"></canvas>
<p id="signatureError" name="signatureError" style="color: red; display: none;">Please provide your signature.</p>
<div class="p-1 text-right">
<button id="resetSignature" class="btn btn-sm" style="background-color: lightblue;">Reset</button>
<button id="saveSignature" class="btn btn-sm" style="background-color: #fbcc34;">Save</button>
</div>
<input type="hidden" name="signature" id="signatureInput">
</div>
</div>
<div class="row">
<div class="col-12 mb-0 pt-2">
<div class="text-right">
<input type="hidden" name="registrationFor" value="customer">
<button type="submit" id="submit" class=" btn next-button bjsh-btn-gradient text-right">Sign Up</button>
</div>
</div>
</div>
var canvas = document.querySelector("canvas");
const signatureSaveButton = document.getElementById("saveSignature");
const signatureResetButton = document.getElementById("resetSignature");
const signatureError = document.getElementById("signatureError");
const signatureInput = document.getElementById("signatureInput");
// Initialize a new signaturePad instance.
var signaturePad = new SignaturePad(canvas);
// Clear signature pad.
signatureResetButton.addEventListener("click", function(event) {
signaturePad.clear();
});
// Save signature pad as data url.
signatureSaveButton.addEventListener("click", function(event) {
if (signaturePad.isEmpty()) {
signatureError.style.display = "block";
} else {
signatureUrl = signaturePad.toDataURL();
signatureInput.value = signatureUrl;
}
});
// Validate registration tab before moving to the next tab
$("#register-form").validate({
rules: {
email: {
required: true,
// Specify that email should be validated
// by the built-in "email" rule
email: true
},
password: {
required: true,
minlength: 8,
},
password_confirmation: {
required: true,
minlength: 8,
equalTo: "#password"
},
full_name: {
required: true
},
nric: {
required: true
},
address_1: {
required: true
},
address_2: {
required: true
},
address_3: {
required: true
},
postcode: {
required: true
},
city: {
required: true
},
state: {
required: true
},
contact_number_home: {
required: true
},
contact_number_mobile: {
required: true
},
existing_customer: {
required: true
},
signatureError: {
required: true
},
},
messages: {
email: {
required: "Please enter an email",
email: "The email is not valid"
},
password: {
required: "Please enter a password",
minlength: "Password must be minimum of 8 characters"
},
password_confirmation: {
required: "Please confirm your password",
minlength: "Passmust must be minimum of 8 characters",
equalTo: "Password must be same as above"
},
full_name: {
required: "Please enter your full name"
},
nric: {
required: "Please enter your identity card number"
},
address_1: {
required: "Please enter your address"
},
address_2: {
required: "Please enter your address"
},
address_3: {
required: "Please enter your address"
},
postcode: {
required: "Please enter your postcode"
},
city: {
required: "Please select your city"
},
state: {
required: "Please select your state"
},
contact_number_home: {
required: "Please enter your home number"
},
contact_number_mobile: {
required: "Please enter your mobile number"
},
signatureError: {
required: "Please provide your signature"
},
}
});
// validate fields in 1st tab
$('#next-btn').click(function() {
if ($("#register-form").validate().element('#email') && $("#register-form").validate().element('#password') && $("#register-form").validate().element('#password-confirm')) {
nextTab.find('a').trigger('click');
} else {}
});
// validate fields in 2nd tab
$('#next-btn2').click(function() {
if ($("#register-form").validate().element('#full_name') && $("#register-form").validate().element('#nric') && $("#register-form").validate().element('#address_1') && $("#register-form").validate().element('#address_2') && $("#register-form").validate().element('#address_3') && $("#register-form").validate().element('#postcode') &&
$("#register-form").validate().element('#city') && $("#register-form").validate().element('#state') && $("#register-form").validate().element('#contact_number_home') &&
$("#register-form").validate().element('#contact_number_mobile') && $("#register-form").validate().element('#existing_customer')
) {
nextTab.find('a').trigger('click');
} else {}
});
// validate signature input in 3rd tab
$('#submit').click(function() {
if ($("#register-form").validate().element('#signatureError')) {
alert("Success");
} else {
alert("Failure");
}
});
If you are using signature_pad by Szymon Nowak then it looks like you set it up correctly.
Edit: OK, I got the signature field to be part of validation. You need to not ignore hidden fields.
Do not validate the error message, LOL. Validate the actual field.
Also, I added a custom validator to handle validating the signature pad, but since it sets the value of the hidden signature field when you hit save, we only need to validate the signature.
Helpful links
https://jqueryvalidation.org/documentation/
https://www.sitepoint.com/basic-jquery-form-validation-tutorial/
jQuery Validate - Enable validation for hidden fields
Example
let $form = $("#register-form");
let canvas = document.querySelector('.signature-pad');
let signatureSaveButton = document.getElementById('saveSignature');
let signatureResetButton = document.getElementById('resetSignature');
let signatureInput = document.querySelector('input[name="signature"]');
// Initialize a new signaturePad instance.
let signaturePad = new SignaturePad(canvas);
// Clear signature pad.
signatureResetButton.addEventListener('click', function(event) {
signaturePad.clear();
signatureInput.value = '';
event.preventDefault();
return false; // prevent submission...
});
// Save signature pad as data url.
signatureSaveButton.addEventListener('click', function(event) {
let signatureBlank = signaturePad.isEmpty();
if (!signatureBlank) {
signatureUrl = signaturePad.toDataURL();
signatureInput.value = signatureUrl;
$("div.error-messages span").html(''); // Clear messages
}
$(signatureInput).valid(); // Call validation on the field after hitting "Save"
event.preventDefault();
return false; // prevent submission...
});
// Not used, because this field has no name. Also, we want to use this
// to set the underlying (hidden) signature field...
$.validator.addMethod('signaturePresent', function(value, element) {
console.log('Checking...');
return this.optional(element) || signaturePad.isEmpty();
}, "Please provide your signature...");
// Validate registration tab before moving to the next tab
$form.validate({
ignore: [], // This is important! We want to validate hidden fields.
rules: {
signature: {
required: true
}
},
messages: {
signature: {
required: "Please provide your signature"
}
},
submitHandler: function(form) {
$("div.error-messages span").html(''); // Clear messages
console.log('Submitting form...');
//form.submit(); <-- UNCOMMENT TO ACTUALLY SUBMIT
},
invalidHandler: function(event, validator) {
console.log('INVALID!');
// 'this' refers to the form
var errors = validator.numberOfInvalids();
if (errors) {
var message = errors == 1
? 'You missed 1 field. It has been highlighted'
: 'You missed ' + errors + ' fields. They have been highlighted';
$("div.error-messages span").html(message);
$("div.error").show();
} else {
$("div.error").hide();
}
}
});
body {
padding: 2em;
}
.signature-pad {
display: block;
border: thin solid grey;
margin: 0 auto;
margin-bottom: 0.5em;
}
.hidden {
display: none !important;
}
form .error {
color: #F00;
}
.error-messages {
text-align: center;
font-size: smaller;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/signature_pad/1.5.3/signature_pad.min.js"></script>
<form id="register-form">
<div class="row">
<div class="col-md-6 text-center">
<label for="signatureInput">Signature</label>
</div>
<div class="form-group text-center">
<canvas class="display-block signature-pad" style="touch-action: none;"></canvas>
<div>
<button id="resetSignature" class="btn btn-sm" style="background-color: lightblue;">Reset</button>
<button id="saveSignature" class="btn btn-sm" style="background-color: #fbcc34;">Save</button>
</div>
<input type="hidden" name="signature" id="signatureInput">
</div>
</div>
<div class="row">
<div class="col-md-6 text-right">
<input type="hidden" name="registrationFor" value="customer">
<button type="submit" id="submit" class=" btn next-button bjsh-btn-gradient text-right">Sign Up</button>
</div>
</div>
</form>
<div class="error-messages"><strong>Messages:</strong><br/><span></span></div>
Having some trouble getting validation to work for Email and Phone on an input field.
Basically I'm after validation on the email input when it is selected. Phone validation - mainly to check for numbers used.
I found jQuery Validate and referenced that in my demo.
This is my first time to Reg Ex Validation and got a little confused so was hoping someone could help me on that front.
The phone validation is working however, I can't seem to figure out how to meet the requirements of the field when testing. It's also asking email as a required field.
Ultimately, a user has to input either a valid email or phone number so validation or error handling will need to be done for that too which I can do.
DEMO HERE
Here is my jQuery:
var ebuForm = {
init : function() {
ebuForm.showInput();
ebuForm.validatePhone();
},
showInput : function(e) {
var radioInput = $("input[type='radio']"),
emailRadio = $("input[value='email']");
radioInput.change(function(){
var emailInput = $('.email-input'),
phoneInput = $('.phone-input');
if($(this).val() =="email") {
emailInput.show();
phoneInput.hide();
console.log('Email Enabled');
} else {
emailInput.hide();
phoneInput.show();
console.log('Phone Enabled');
}
});
emailRadio.prop('checked', true).trigger("change");
},
validatePhone : function() {
$('#myform').validate({
rules: {
phone: {
phoneUS: true,
required: true
}
},
submitHandler: function(form) { // for demo
alert('valid form');
return false;
}
});
}
};
$(function() {
ebuForm.init();
});
Working Fiddle Example: http://jsfiddle.net/775X2/56/
Your HTML:
<form id="myform">
<div class="grid4">
<input type="radio" checked="checked" tabindex="50" class="left" name="x" id="email" value="email" />
<label for="email" class="left marginRight20">Email</label>
<input type="radio" tabindex="60" class="left" name="x" id="phone" />
<label for="phone" class="left">Phone</label>
<br />
<input type="text" class="email-input" name="emailer" placeholder="Email Address" />
<input type="text" class="phone-input" name="phone" placeholder="Phone Number" />
</div>
</form>
Validation Documentation
Some jQuery:
var ebuForm = {
init: function () {
ebuForm.showInput();
ebuForm.validatePhone();
},
showInput: function (e) {
var radioInput = $("input[type='radio']"),
emailRadio = $("input[value='email']");
radioInput.change(function () {
var emailInput = $('.email-input'),
phoneInput = $('.phone-input');
if ($(this).val() == "email") {
emailInput.show();
phoneInput.hide();
console.log('Email Enabled');
} else {
emailInput.hide();
phoneInput.show();
console.log('Phone Enabled');
}
});
emailRadio.prop('checked', true).trigger("change");
},
validatePhone: function () {
$('#myform').validate({
rules: {
phone: {
phoneUS: true,
required: true
},
emailer: {
required: true,
email: true
},
},
submitHandler: function (form) { // for demo
alert('valid form');
return false;
}
});
}
};
$(function () {
ebuForm.init();
});
This is my code, checkUsername function doesn't working, how should I fixit?
<form id="register_form" method="post" action="">
<fieldset>
<legend>Info</legend>
<div>
<label>Username</label>
<input type="text" name="username" id="username"/>
<input type="submit" id="btnAccess" class="button" value="Submit" name="btnAccess"/>
</fieldset>
</form>
$(document).ready(function() {
var validator = $('#register_form').validate({
rules: {
username: {
required: true,
minlength: 4,
checkUsername: true
}
},
messages: {
username: {
required: "No blank",
minlength: "Enter atleast 4 words"
}
}
});
$.validator.addMethod('checkUsername', function(value, element) {
return /\s/g.test(value);
}, "error");
});
http://jsfiddle.net/nambatre/rEpqr/
P/S: if I want to check a string has some words as #, # etc, what should I do?
You need to return true is the the value is true
it should be
$.validator.addMethod('checkUsername', function(value, element) {
return this.optional(element) || !/\s/g.test(value);
}, "error");
Demo: Fiddle
I am using the following JQuery validation:
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
I have the following element:
<div class="form-item">
<label for="Reference_name" class="required">Name: <span class="required">*</span></label>
<input name="Reference[name][]" class="form-input validate {validate:{required:true,minLength:2,messages:{required:'Your name is required',minLength:'Your name is too short'}}}" id="Reference_name" type="text">
</div>
I have cloned the element but the validation is only appearing on the first element. I would like it to validate against the second too and show the error message label.
Can someone help with this please.
elements must be unique
<label for="Reference_name" class="required">Name:<span class="required">*</span></label>
<input type="text" id="Reference_name" name="Reference[Name]" id="Reference_name" required="required" maxlength="255" />
File Js
$(document).ready(function() {
validate_form();
});
function validate_form() {
$("#id_of_your_form").validate({
rules: {
'Reference_name': {
required:true,
minlength: 2,
}
},
},
messages: {
'Reference_name': {
required:"Your name is required",
minLength:'Your name is too short'
},
}
});
}
if you want to compare two fields
http://docs.jquery.com/Plugins/Validation/Methods/equalTo#other
Put your validation function in a global variable like this:
var validate_form_function = function(){
if($(".app-form").length > 0){
$('.app-form').validate({
rules: {
comment_message: {
required: true,
minlength: 2
}
},
messages: {
comment_message: {
required: "Your message",
minlength: "Your message"
}
}
});
}
};
Then revalidate your cloned form with the function like this :
validate_form_function();
How do you create a simple, custom rule using the jQuery Validate plugin (using addMethod) that doesn't use a regex?
For example, what function would create a rule that validates only if at least one of a group of checkboxes is checked?
You can create a simple rule by doing something like this:
jQuery.validator.addMethod("greaterThanZero", function(value, element) {
return this.optional(element) || (parseFloat(value) > 0);
}, "* Amount must be greater than zero");
And then applying this like so:
$('validatorElement').validate({
rules : {
amount : { greaterThanZero : true }
}
});
Just change the contents of the 'addMethod' to validate your checkboxes.
$(document).ready(function(){
var response;
$.validator.addMethod(
"uniqueUserName",
function(value, element) {
$.ajax({
type: "POST",
url: "http://"+location.host+"/checkUser.php",
data: "checkUsername="+value,
dataType:"html",
success: function(msg)
{
//If username exists, set response to true
response = ( msg == 'true' ) ? true : false;
}
});
return response;
},
"Username is Already Taken"
);
$("#regFormPart1").validate({
username: {
required: true,
minlength: 8,
uniqueUserName: true
},
messages: {
username: {
required: "Username is required",
minlength: "Username must be at least 8 characters",
uniqueUserName: "This Username is taken already"
}
}
});
});
// add a method. calls one built-in method, too.
jQuery.validator.addMethod("optdate", function(value, element) {
return jQuery.validator.methods['date'].call(
this,value,element
)||value==("0000/00/00");
}, "Please enter a valid date."
);
// connect it to a css class
jQuery.validator.addClassRules({
optdate : { optdate : true }
});
Custom Rule and data attribute
You are able to create a custom rule and attach it to an element using the data attribute using the syntax data-rule-rulename="true";
So to check if at least one of a group of checkboxes is checked:
data-rule-oneormorechecked
<input type="checkbox" name="colours[]" value="red" data-rule-oneormorechecked="true" />
addMethod
$.validator.addMethod("oneormorechecked", function(value, element) {
return $('input[name="' + element.name + '"]:checked').length > 0;
}, "Atleast 1 must be selected");
And you can also override the message of a rule (ie: Atleast 1 must be selected) by using the syntax data-msg-rulename="my new message".
NOTE
If you use the data-rule-rulename method then you will need to make sure the rule name is all lowercase. This is because the jQuery validation function dataRules applies .toLowerCase() to compare and the HTML5 spec does not allow uppercase.
Working Example
$.validator.addMethod("oneormorechecked", function(value, element) {
return $('input[name="' + element.name + '"]:checked').length > 0;
}, "Atleast 1 must be selected");
$('.validate').validate();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.14.0/jquery.validate.min.js"></script>
<form class="validate">
red<input type="checkbox" name="colours[]" value="red" data-rule-oneormorechecked="true" data-msg-oneormorechecked="Check one or more!" /><br/>
blue<input type="checkbox" name="colours[]" value="blue" /><br/>
green<input type="checkbox" name="colours[]" value="green" /><br/>
<input type="submit" value="submit"/>
</form>
Thanks, it worked!
Here's the final code:
$.validator.addMethod("greaterThanZero", function(value, element) {
var the_list_array = $("#some_form .super_item:checked");
return the_list_array.length > 0;
}, "* Please check at least one check box");
You can add a custom rule like this:
$.validator.addMethod(
'booleanRequired',
function (value, element, requiredValue) {
return value === requiredValue;
},
'Please check your input.'
);
And add it as a rule like this:
PhoneToggle: {
booleanRequired: 'on'
}
For this case: user signup form, user must choose a username that is not taken.
This means we have to create a customized validation rule, which will send async http request with remote server.
create a input element in your html:
<input name="user_name" type="text" >
declare your form validation rules:
$("form").validate({
rules: {
'user_name': {
// here jquery validate will start a GET request, to
// /interface/users/is_username_valid?user_name=<input_value>
// the response should be "raw text", with content "true" or "false" only
remote: '/interface/users/is_username_valid'
},
},
the remote code should be like:
class Interface::UsersController < ActionController::Base
def is_username_valid
render :text => !User.exists?(:user_name => params[:user_name])
end
end
Step 1 Included the cdn like
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
Step 2 Code Like
$(document).ready(function(){
$("#submit").click(function () {
$('#myform').validate({ // initialize the plugin
rules: {
id: {
required: true,
email: true
},
password: {
required: true,
minlength: 1
}
},
messages: {
id: {
required: "Enter Email Id"
},
password: {
required: "Enter Email Password"
}
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
}):
});