Change RegEx Validation on textbox based on dropdown selection - jquery-validate

I have a working example of replacing Validation methods based on a dropdown's selection.
The issue I'm having is using a regex with the JQueryValidation, entering a valid Twitter address always returns the Invalid Address error.
The below function runs when the Page loads, I set the Default Validation, then I add new validation when the dropdown is changed.
jsFiddle - here
ValidationDefaults();
//Setup all .Select2
$(".select2").select2({
theme: 'bootstrap4',
placeholder: '- Search -',
});
$('#SocialMediaNetworkId').on('select2:select', function(e) {
var data = e.params.data;
AccountNameLabel(data.id);
});
$('#btnSubmit').on('click', function(e) {
if ($("form").valid()) {
/* $('#Edit').submit();*/
}
});
function AccountNameLabel(SocialMediaNetworkId) {
$("#Edit").data('validator').resetForm();
switch (parseInt(SocialMediaNetworkId)) {
case 1:
$("label[for='SocialMediaAccountName']").text("FaceBook Url");
$("#SocialMediaAccountName").attr("placeholder", "FaceBook Url - Ex. https://www.FaceBook.com/joeblow");
FaceBookValidation();
break;
case 2:
$("label[for='SocialMediaAccountName']").text("YouTube Url");
$("#SocialMediaAccountName").attr("placeholder", "YouTube Url - Ex. https://www.YouTube.com/joeblow");
YouTubeValidation();
break;
case 3:
$("label[for='SocialMediaAccountName']").html("Twitter Url");
$("#SocialMediaAccountName").attr("placeholder", "Twitter Url - Ex. https://www.twitter.com/joeblow");
TwitterValidation();
break;
case 4:
$("label[for='SocialMediaAccountName']").text("Instagram Url");
$("#SocialMediaAccountName").attr("placeholder", "Instagram Url - Ex. https://www.Instagram.com/joeblow");
InstagramValidation();
break;
}
}
function ValidationDefaults() {
$('#Edit').validate({
rules: {
SocialMediaNetworkId: {
required: true
}
},
messages: {
SocialMediaNetworkId: "* Required Field"
},
errorElement: 'span',
errorPlacement: function(error, element) {
error.addClass('invalid-feedback');
element.closest('.form-group').append(error);
},
highlight: function(element, errorClass, validClass) {
$(element).addClass('is-invalid');
},
unhighlight: function(element, errorClass, validClass) {
$(element).removeClass('is-invalid');
}
});
}
function TwitterValidation() {
var settings = $('#Edit').validate().settings;
$("#SocialMediaAccountName").rules("remove");
$("#SocialMediaAccountName").rules("add",
{
required: true,
pattern: "/http(?:s)?:\/\/(?:www\.)?twitter\.com\/([a-zA-Z0-9_]+)/",
messages: {
required: "Required input",
pattern: "* Must be a valid Twitter URL - Ex. https://www.twitter.com/joeblow"
}
}
);
//$("#SocialMediaAccountName").rules("add", {
// required: true,
// pattern: {
// required: "/http(?:s)?:\/\/(?:www\.)?twitter\.com\/([a-zA-Z0-9_]+)/"
// },
// messages: {
// required: "Required input",
// pattern: "* Must be a valid Twitter URL - Ex. https://www.twitter.com/joeblow"
// }
//});
//// Modify validation settings
//$.extend(true, settings, {
// rules: {
// // Add validation
// "SocialMediaAccountName": {
// required: true,
// pattern: "/http(?:s)?:\/\/(?:www\.)?twitter\.com\/([a-zA-Z0-9_]+)/"
// }
// }
//});
//$.extend(jQuery.validator.messages, {
// required: "* Required Field.",
// pattern: "* Must be a valid Twitter URL - Ex. https://www.twitter.com/joeblow"
//});
}

Related

Backbone-validation.js on Subview

I've been following an online example of backbone validation online:
http://jsfiddle.net/thedersen/c3kK2/
So far so good, but now I'm getting into validating subviews and they're not working.
My code looks like this:
var ScheduleModel = Backbone.Model.extend({
validation: {
StartDate: {
required: true,
fn: "isDate"
},
StartTime: [{
required: true
},
{
pattern: /^([0-2]\d):([0-5]\d)$/,
msg: "Please provide a valid time in 24 hour format. ex: 23:45, 02:45"
}],
EndDate: {
required: true,
fn: "isDate"
}
},
isDate: function (value, attr, computed) {
if (isNaN(Date.parse(value))) {
return "Is not a valid Date";
}
}
});
var ScheduleView = Backbone.View.extend({
tagName: "div",
template: _.template($("#scheduleAddTemplate").html()),
render: function () {
// append the template to the element
this.$el.append(this.template(this.model.toJSON()));
// set the schedule type
var renderedInterval = SetScheduleType(this.model.attributes.ScheduleType.toLowerCase());
// append to the interval
$("#Interval", this.$el).append(renderedInterval.el);
this.stickit();
return this;
},
events: {
"submit #NewScheduleForm": function (e) {
e.preventDefault();
if (this.model.isValid(true)) {
this.model.save(null,
{
success: function (schedule) {
//do stuff
}
},
{ wait: true });
}
}
},
bindings: {
"[name=ScheduleType]": {
observe: "ScheduleType",
setOptions: {
validate: true
}
},
"[name=StartDate]": {
observe: "StartDate",
setOptions: {
validate: true
}
},
"[name=StartTime]": {
observe: "StartTime",
setOptions: {
validate: true
}
},
"[name=EndDate]": {
observe: "EndDate",
setOptions: {
validate: true
}
}
},
initialize: function () {
Backbone.Validation.bind(this);
},
remove: function () {
Backbone.Validation.unbind(this);
}
});
The possible interval I'm currently working with is the following:
var MonthModel = Backbone.Model.extend({
defaults: {
DayOfMonth: 1,
MonthsToSkip: 1
},
MonthsToSkip: {
required: true,
min: 1,
msg: "Number must be greater than 1"
},
DayOfMonth: {
required: function (val, attr, computed) {
console.log(computed.ScheduleType);
if (computed.ScheduleType === "monthly") {
return true;
}
return false;
}
}
});
var MonthlyView = Backbone.View.extend({
tagName: "div",
attributes: function () {
return { id: "Monthly", class: "inline co-xs-4" };
},
template: _.template($("#monthEditTemplate").html()),
render: function () {
// append the template to the element
this.$el.append(this.template(this.model.toJSON()));
this.stickit();
return this;
},
bindings: {
"[name=DayOfMonth]": {
observe: "DayOfMonth",
setOptions: {
validate: true
}
},
"[name=MonthsToSkip]": {
observe: "MonthsToSkip",
setOptions: {
validate: true
}
}
},
initialize: function () {
Backbone.Validation.bind(this);
},
remove: function () {
Backbone.Validation.unbind(this);
}
});
Does anyone have any idea why the subview isn't validating?
Found the way to do it. Posting how it's done in case anyone else ever finds this a problem. I'm only going to show the relevant bits of code without all the bindings, initializing ect.
var ScheduleView = Backbone.View.extend({
render: function () {
// this.Interval
this.Interval = SetScheduleType(this.model.attributes.ScheduleType.toLowerCase(), this.model);
// set the changed interval view
$("#Interval", this.$el).append(this.Interval.render().el);
this.stickit();
return this;
},
events: {
"change #NewScheduleForm": function (e) {
// validate the subview when changes are made
this.Interval.model.validate();
},
"change #ScheduleType": function (e) {
e.preventDefault();
var model = this.model;
var newSchedType = e.target.value;
this.model.attributes.ScheduleType = e.target.value;
this.Interval = SetScheduleType(newSchedType, model);
$("#Interval").html(this.Interval.render().el);
},
"submit #NewScheduleForm": function (e) {
e.preventDefault();
if ((this.model.isValid(true)) && (this.Interval.model.isValid(true))) {
console.log("Success");
this.model.save(null,
{
success: function (schedule) {
//do stuff
}
},
{ wait: true });
}
}
}
});
Essentially I turned the subview into an attribute on the master view. I manually call the validation for the subview on any changes to the master view and on submitting the form.

Custom function only for edit mode, not add mode, in jqGrid

I have a jqGrid custom function as editrules: { custom: true, custom_func: checkforduplicates, required:true }
However, I want this function to be run only in add mode, not in edit mode. Is this possible ?
EDIT:- After answer below from Oleg, I changed code to below. However, the alert does not print. Not sure where I am going wrong.
colModel: [
{ key: true, name: 'id', editable: false, formatter: 'integer', viewable: false, hidden: true },
{
key: false,
name: 'name',
editable: true,
editrules: {
required: true,
custom: function (options) {
// options have the following properties
// cmName
// cm
// iCol
// iRow
// rowid
// mode - "editForm", "addForm", "edit", "add", "cell" and so on
// newValue - the value which need be validated
// oldValue - the old value
// some additional properties depends on the editing mode
alert("mode is " + options.mode);
if (options.mode === "add") { // "add" for inline editing
var grid = $("#grid");
var textsLength = grid.jqGrid("getRowData");
var textsLength2 = JSON.stringify(textsLength);
alert("i am here");
var myAttrib = $.map(textsLength,
function (item) { return item.name });
var count = 0;
for (var k in textsLength) {
if (textsLength.hasOwnProperty(k)) {
++count;
}
}
var text, i;
for (i = 0; i < count; i++) {
text = myAttrib[i];
if (value === text) {
return [false, " - Duplicate category name."];
}
}
return [true, ""];
}
return true;
}
}
},
Free jqGrid supports old style custom_func with the options value, name and iCol and the new style validation. To use new style validation one don't need to specify any custom_func callback, but to define custom as the calback function with one parameter:
editrules: {
required: true,
custom: function (options) {
// options have the following properties
// cmName
// cm
// iCol
// iRow
// rowid
// mode - "editForm", "addForm", "edit", "add", "cell" and so on
// newValue - the value which need be validated
// oldValue - the old value
// some additional properties depends on the editing mode
if (options.mode === "addForm") { // "add" for inline editing
// do the validation
}
return true;
}
}
In case of validation of Add form the mode property is equal to "addForm", options.iRow === -1, options.oldValue === null, options.rowid === "_empty". It's recommended to use options.mode to detect the editing (or searching mode) in free jqGrid because the values of other properties (iRow, oldValue and rowid) depends on the editing mode.
For version 4.7 I use this method. Form for adding data class for the table. After that, special actions verified by the user are performed.
{
name : "LOGIN",
index : "LOGIN", editrules: {
required:true,
custom:true,
custom_func: dublicateUser
}
...
{
closeAfterAdd : true,
width : 500,
recreateForm : true,
afterShowForm : function () {
jQuery("#TblGrid_list_users").addClass('addMode');
}
...
function dublicateUser() {
var a;
var login = jQuery('#LOGIN').val();
var checkMode = jQuery('#TblGrid_list_users').hasClass('addMode');
jQuery.ajax({
type: 'POST',
data: {login:login, mode:checkMode},
url: 'code/validate_user.php',
async: false,
success: function(data) {
if (data == 'err') {
a = 1;
}
else {
a=0;
}
}
});
if (a==1) {
return[false,"error"];
}
else {
return[true];
}
}

Multiple SqPaymentForms in one webpage

I am using Square credit card processing, I have to use two payment forms in same webpage one is for pickup payment and other for delivery payment.
I tried to integrate SqPaymentForm in my webpage i was successful for pickup payment. when it comes to delivery may be formwas loading twice and I have to enter all my card details twice in the form. How can i over come this problem?
var paymentFormUserPickUp = new SqPaymentForm({
applicationId: ApplicationId,
inputClass: 'sq-input',
cardNumber: {
elementId: 'sq-card-numberup',
placeholder: 'Card Number'
},
cvv: {
elementId: 'sq-cvvup',
placeholder: 'CVV'
},
expirationDate: {
elementId: 'sq-expiration-dateup',
placeholder: 'MM/YY'
},
postalCode: {
elementId: 'sq-postal-codeup',
placeholder: 'Zip Code'
},
callbacks: {
cardNonceResponseReceived: function (errors, nonce, cardData) {
if (errors) {
// handle errors
var Errors;
errors.forEach(function (error) {
Errors += error.message + ",";
});
Errors.trimEnd(',');
alert(Errors);
} else {
alert(nonce);
localStorage.setItem("Nonce", nonce);
}
},
unsupportedBrowserDetected: function () {
// Alert the buyer that their browser is not supported
}
}
});
var paymentFormUserDelivery = new SqPaymentForm({
applicationId: ApplicationId,
inputClass: 'sq-input',
cardNumber: {
elementId: 'sq-card-numberud',
placeholder: 'Card Number'
},
cvv: {
elementId: 'sq-cvvud',
placeholder: 'CVV'
},
expirationDate: {
elementId: 'sq-expiration-dateud',
placeholder: 'MM/YY'
},
postalCode: {
elementId: 'sq-postal-codeud',
placeholder: 'Zip Code'
},
callbacks: {
cardNonceResponseReceived: function (errors, nonce, cardData) {
if (errors) {
// handle errors
var Errors;
errors.forEach(function (error) {
Errors += error.message + ",";
});
Errors.trimEnd(',');
alert(Errors);
} else {
alert(nonce);
localStorage.setItem("Nonce", nonce);
}
},
unsupportedBrowserDetected: function () {
// Alert the buyer that their browser is not supported
}
}
});
Thanks!!!
There is no support for multiple forms for a single card input. Why does an order take both pickup and delivery payments? Do you have a sample page?

After closing the modal dialog refresh the base view

suggestion and code sample
I am new to Backbone marionette, I have a view ("JoinCommunityNonmemberWidgetview.js") which opens a modal dialog ("JoinCommunityDetailWidgetview.js").On closing of the dialog ( I want the view JoinCommunityNonmemberWidgetview.js") to be refreshed again by calling a specific function "submitsuccess" of the view JoinCommunityNonmemberWidgetview.js.
How can I achieve it.
The code for the modal is as below:
define(
[
"grads",
"views/base/forms/BaseFormLayout",
"models/MembershipRequestModel",
"require.text!templates/communitypagewidget/JoinCommunityWidgetDetailTemplate.htm",
],
function (grads, BaseFormLayout, MembershipRequestModel, JoinCommunityWidgetDetailTemplate) {
// Create custom bindings for edit form
var MemberDetailbindings = {
'[name="firstname"]': 'FirstName',
'[name="lastname"]': 'LastName',
'[name="organization"]': 'InstitutionName',
'[name="email"]': 'Email'
};
var Detailview = BaseFormLayout.extend({
formViewOptions: {
template: JoinCommunityWidgetDetailTemplate,
bindings: MemberDetailbindings,
labels: {
'InstitutionName': "Organization"
},
validation: {
'Email': function (value) {
var emailconf = this.attributes.conf;
if (value != emailconf) {
return 'Email message and Confirm email meassage should match';
}
}
}
},
editViewOptions: {
viewEvents: {
"after:render": function () {
var self = this;
var btn = this.$el.find('#buttonSubmit');
$j(btn).button();
}
}
},
showToolbar: false,
editMode: true,
events: {
"click [data-name='buttonSubmit']": "handleSubmitButton"
},
beforeInitialize: function (options) {
this.model = new MembershipRequestModel({ CommunityId: this.options.communityId, MembershipRequestStatusTypeId: 1, RequestDate: new Date() });
},
onRender: function () {
BaseFormLayout.prototype.onRender.call(this)
},
handleSubmitButton: function (event) {
this.hideErrors();
// this.model.set({ conf: 'conf' });
this.model.set({ conf: this.$el.find('#confirmemail-textbox').val() });
//this.form.currentView.save();
//console.log(this.form);
this.model.save({}, {
success: this.saveSuccess.bind(this),
error: this.saveError.bind(this),
wait: true
});
},
saveSuccess: function (model, response) {
var mesg = 'You have submitted a request to join this community.';
$j('<div>').html(mesg).dialog({
title: 'Success',
buttons: {
OK: function () {
$j(this).dialog('close');
}
}
});
grads.modal.close();
},
saveError: function (model, response) {
var msg = 'There was a problem. The request could not be processed.Please try again.';
$j('<div>').html(msg).dialog({
title: 'Error',
buttons: {
OK: function () {
$j(this).dialog('close');
}
}
});
}
});
return Detailview;
}
);
I would use Marionette's event framework.
Take a look at: https://github.com/marionettejs/backbone.marionette/blob/master/docs/marionette.commands.md
Specifically, you need to:
1) Create a marionette application :
App = new Marionette.Application();
2) Use the application to set up event handlers
//Should be somewhere you can perform the logic you are after
App.commands.setHandler('refresh');
3) Fire a 'command' and let marionette route the event
App.execute('refresh');

Signature Pad Validation

I have a multipage form using jqm. The last two pages uses Thomas j bradleys signature pad. I use jquery validate plugin to validate each page before it moves on.
I can not get jquery validate plugin to verify if the is a signature.
This is the code I use for the validation. All this works fine just need to add the signature validation in.
$("#breakinform").validate({
rules: {
sitename: {
required: true,
},
Address: {
required: true,
},
BreakInDate: {
required: true,
},
recafcheckbox: {
required: true,
},
sigPad: {
required: true,
},
},
messages: {
sitename: {
required: "Please Enter Site Name",
},
Address: {
required: "Please Enter Address",
},
BreakInDate: {
required: "Please Enter Date",
},
recafcheckbox: {
required: "Please Confirm",
},
sigPad: {
required: "Please Sign In The Box",
},
}
});
//break
$("a.check").click(function(){
if($("#breakinform").valid()){
} else {
navigator.notification.alert(
"Please Fill In The Required Fields!",
callBackFunctionB, // Specify a function to be called
'Missing Data',
"OK"
);
function callBackFunctionB(){
console.log('ok');
}
return false;
}
});
A workaround that I used by adding the following to my "submitHandler":
var result = true;
if ($('.sigPad input.output').length)
{
$('.sigPad input.output').each(function(){
if ($(this).val().length == 0) result = false; });
}
if (!result ) return false;
and keeping signaturePad's "validateFields" option to true.
#Hunty3000, I don't think you'll be able to use the jQuery validate plugin to validate your canvas so why not use Signature Pad's built in validation?
Here's how:
http://thomasjbradley.ca/lab/signature-pad/#accept-form
If you need more assistance, don't hesitate to ask.

Resources