using jquery to validate postal code based on country - jquery-validate

Working on site where we currently accept US zip codes. I already have jquery validate working for that. What i want to do now is add a drop down for the user to select country, and then based on the country they selected, it will validate the postal code to make sure it matches.
Can someone give me some pointers on how i can do this? Basically, i just need to change the regex the validator function is using based on the country drop down. The (what i assume is) relevant section of the jquery validator function is this:
(function ($) {
$.fn.validate = function (options) {
var defaults = {
invalidClass: 'error',
rules: {
req: /.{1,}/g,
email: /[\w\.=-]+#[\w\.-]+\.[\w]{2,3}/g,
phone: /\D?(\d{3})\D?\D?(\d{3})\D?(\d{4})/g,
zip: /\d{5}$|^\d{5}-\d{4}/g,
//password: /^(?=.*\d)(?=.*[a-zA-Z]).{8,20}$/g,
password: /^(?=.{8,20}$)(?=.*\d)(?=.*[a-zA-Z]).*/g,
//nospecialchars: /[^<>?,\/\\\[\]\{\}\|!##$%^&*()_+;:"]{1,}/g
nospecialchars: /^(?!.*[?<>;]).+$/g
},
error_messages: {
req: 'Oops..',
email: 'Please enter your email address.',
phone: '',
zip: 'Please give me a valid zip.',
max: 'too many characters.',
password: '',
nospecialchars: ''
},
success: null,
failure: null
},
errors = [],
opts = $.extend(true, defaults, options);
return this.each(function () {
var $this = $(this);
$(this).find('input[type="submit"]:not(.cancel), button').click(function () {
errors = [];
validate_fields($this);
if ($this.find('.error').length === 0) {
if (typeof opts.success == 'function')
return opts.success();
}
else {
if (typeof opts.failure == 'function')
return opts.failure(errors);
}
});
});
I'm not very familiar with jquery so i don't know what the syntax is here for me to create an if-else or case statement to set the regex.
Thanks if advance for any help.
edit: Here's the bit of code that actually calls the validation
<script type="text/javascript">
$(function () {
setForm();
$('form').validate({
error_messages: {
req: null
},
failure: function (errors) {
var sel = '';
$(".errMsg").hide();
for (x in errors) {
sel += ',#' + errors[x][0];
}
if (sel.length > 0) {
sel = sel.substring(1);
$(sel).parent().find(".errMsg").show(0, function () {
$('#home .orange_box, #home .HomeRight').height('auto');
$('#infov .white_box, #infov .orangeRight').height('auto');
$('#findt .orange_box, #findt .HomeRight').height('auto');
if ($.browser.msie && $.browser.version == 8) {
evenColumns('#home .orange_box', '#home .HomeRight', -16);
evenColumns('#infov .white_box', '#infov .orangeRight', -16);
evenColumns('#findt .orange_box', '#findt .HomeRight', -16);
}
else {
evenColumns('#home .orange_box', '#home .HomeRight', -15);
evenColumns('#infov .white_box', '#infoforv .orangeRight', -15);
evenColumns('#findt .orange_box', '#findt .HomeRight', -15);
}
});
}
return false;
},
success: function () {
$(".errMsg").hide();
return true;
}
});

I would create an object, witch has:
function for the validation
object for all other countries
object for default rules
validation = {
validate : function( sCountryName, sToValidate ){
return ( null != sToValidate.match( this.countries[ sCountryName ] ? this.countries[ sCountryName ].zip : this.defaultRules.zip ))
},
countries : {
england : {
zip : /\d{5}$|^\d{5}-\d{4}/g
}
},
defaultRules : {
zip : /\d{5}$|^\d{5}-\d{4}/g
}
}

Related

ajax request concatenate jason in data object

i have ajax request and i call the api in the action and in js i create vars input's
my api need to get json so
i'll try to concatenate jason in data object but i get syntax errors
what am i doing wrong?
thanks for the help
<script>
function postForm() {
var name = document.forms["form"]["name"].value;
var phone = document.forms["form"]["phone"].value.replace("-", "");
var email = document.forms["form"]["email"].value;
if (name === "" || phone === "" || email === "") {
window.alert("עלייך למלא את כל השדות");
return false;
}
if (!validatePhone(phone)) {
window.alert("הכנס מספר טלפון תקין");
return false;
}
if (!validateEmail(email)) {
window.alert("כתובת המייל שהזנת אינה חוקית");
return false;
}
if (!validateName(name)) {
window.alert("הכנס שם באותיות רווחים");
return false;
}
return true;
$.ajax({
url: $('form').attr('action'),
method: "get",
dataType:'json',
data: {"name": "name", "phone": "phone", "email: email", "details": "details"},
success: function () {
console.log(data);
},
error: function() {
window.alert("משהו לא הלך כשורה");
}
});
}

Knockout JS validation message repeating twice

New to Knockoutjs, Just trying to fix an existing bug in validation message. Below mentioned extend validation messages repeating twice in the UI.
$.each(viewModel.Form.Questions(), function () {
var currentQuestion = this;
debugger;
$.each(currentQuestion.QuestionAnswers(), function () {
var text = this.AnswerDisplay();
this.AnswerValue.extend({
required: {
message: text + " : Question price is required",
onlyIf: function () {
return viewModel.Form.FormPrice.PricingMode() == 2;
}
},
min: {
message: text + " : Question price should be a number",
onlyIf: function () {
return viewModel.SelectedQuestion() != null && currentQuestion.FormQuestionId() == viewModel.SelectedQuestion().FormQuestionId() && viewModel.Form.FormPrice.PricingMode() == 2;
},
params: 0
}
});
});
});

How do I include an Ajax validator before sending

I managed to make this code to submit a form, it works fine, but I can not implement a validator does not need it, but it shows no message just does not send the form is empty.
I searched but could not quite do it. Can anyone help me?
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('#newsletter').submit(function(){
var dados = jQuery( this ).serialize();
jQuery.ajax({
type: "POST",
url: "newsletter_cadastrar.asp?f=1",
data: dados,
success: function( data )
{
$('#resultado-form-newsletter').html(data);
}
});
return false;
});
});
</script>
<input id="nomenewslbase" name="nomenewslbase" type="text">
<input id="emailnewslbase" name="emailnewslbase" type="email">
Thank you for your attention.
If you are looking for applying jquery validation rules then you can do it like:
<script type="text/javascript">
function ValidationRules() {
}
ValidationRules.prototype.initializeSaveValidators = function() {
jQuery.validator.addMethod("csProjectName",
function(value, element) {
if ($.trim($('#txtProjectName').val()) == "") {
if ($.trim($(element).val()) != '')
return true;
else
return false;
} else
return true;
}, "Project Name is required");
jQuery.validator.addMethod("csDescription",
function (value, element) {
if ($.trim($('#txtDescription').val()) == "") {
if ($.trim($(element).val()) != '')
return true;
else
return false;
}
else
return true;
}, "Description is required");
};
ValidationRules.prototype.enableSaveValidators = function () {
jQuery.validator.classRuleSettings.csProjectName = { csProjectName: true };
jQuery.validator.classRuleSettings.csDescription = { csDescription: true };
};
ValidationRules.prototype.disableSaveValidators = function () {
jQuery.validator.classRuleSettings.csProjectName = { csProjectName: false };
jQuery.validator.classRuleSettings.csDescription = { csDescription: false };
};
jQuery(document).ready(function () {
var validationRules = new ValidationRules();
validationRules.initializeSaveValidators();
validationRules.enableSaveValidators();
$("#btnsubmit").click(function () {
applyjQueryValidation();
return false;
});
});
function applyjQueryValidation() {
var isValid = $('#newsletter').valid();
//here you can manually check for some extra validations
if (isValid==true) {
alert("valid");
//here is you ajax call
}else{
alert("invalid");
}
}
</script>
Also, you need to include jquery.validate.js
Here is the JSfiddle working example.

knockout validation for array of objects

I have an array of dynamically added objects and I want to validate this array for required fields and numeric values.
I have 3 buttons, one for adding note, another for removing note and one for saving
How to validate every object ?
.. the code:
$(function () {
var initialData = [{
Title: "",
NoteText: "",
Suggestion: "",
MediaTime: ""
}];
var CreateNewNoteModel = function (Notes) {
var self = this;
self.Notes = ko.observableArray(ko.utils.arrayMap(Notes, function (Note) {
return { Title: Note.Title, NoteText: Note.NoteText, Suggestion: Note.Suggestion, MediaTime: Note.MediaTime };};
}));
var i = 1;
self.addNote = function () {
self.Notes.push({
Title: "", NoteText: "", Suggestion: "", MediaTime: ""
});
$('#editor' + i).wysihtml5();
$('#editorB' + i).wysihtml5();
i++;
};
self.removeNote = function (Note) {
self.Notes.remove(Note);
};
self.save = function () {
self.lastSavedJson(JSON.stringify(ko.toJS(self.Notes), null, 2));
var jsondata = self.lastSavedJson();
$.ajax({
url: "/api/Notes/?mid=" + m + "&p=" + p,
cache: false,
type: 'Post',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: jsondata,
success: function () {
alert("Success");
document.location.reload(true);
}
});
};
self.lastSavedJson = ko.observable("")
};
ko.applyBindings(new CreateNewNoteModel(initialData));
});
I am using jQuery validate plugin to add validation to knockout-js by using jQuery's validation methods: "$.validator.addMethod" and "$.validator.addClassRules".
Example:
First define your validation methods and css classes. Later on, we add the css classes to your inputs to validate your fields.
function DefineValidationRules() {
$.validator.addMethod("validateNumber", ValidateInteger, "This field is not a number");
$.validator.addMethod("validateRequired", $.validator.methods.required, "This field is required");
$.validator.addMethod("validateMin", $.validator.methods.min, $.format("This number be greater than or equal to {0}"));
$.validator.addMethod("validateMax", $.validator.methods.min, $.format("This number must be less than or equal to {0}"));
$.validator.addMethod("validateMinlength", $.validator.methods.minlength, $.format("This field must contain at least {0} characters"));
$.validator.addMethod("validateRangelength", $.validator.methods.rangelength, $.format("This field must contain between {0} and {1} characters"));
$.validator.addClassRules("validate-number", { validateNumber: true });
$.validator.addClassRules("validate-number-min", { validateNumber: true, validateMin: 1 });
$.validator.addClassRules("validate-required-number-min", { validateRequired: true, validateNumber: true, validateMin: 1 });
$.validator.addClassRules("validate-required", { validateRequired: true });
$.validator.addClassRules("validate-rangelengthmax6", { validateRangelength: [0,6] });
}
DefineValidationRules();
You can also add your own custom validation method:
function ValidateInteger(value) {
//do whatever you want to check
}
Having an input in knockout:
<input class="validate-required validate-number" type="text" data-bind="value: examplefield, valueUpdate: 'afterkeydown', attr: { attrname: 'itsvalue'}" />
Checking on submit:
$("#yoursubmitbutton").on("click", function () {
var formtosubmit = $("#idofyourform");
//check for validation errors
if (isValid(formtosubmit)) {
formtosubmit.submit();
//
// code to proceed to next step
}
});
function isValid(el) {
var $thisform = el;
$thisform.validate({
errorElement: "label",
errorPlacement: function (error, element) {
//eventual different error placing
if (element.attr("name") == "fname" || element.attr("name") == "lname") {
element.css("border", "2px solid red");
error.insertAfter("#lastname");
} else {
error.insertAfter(element);
}
}
});
return $thisform.valid();
}

Backbone collection fetch error with no information

I have a strange problem with the fetch of a backbone collection I am working with. In one particular instance of my code I perform a fetch (exactly how I do it in other areas of the code which all work fine), the fetch never seems to make it to the server and the developer tools shows the request as red with the word (canceled) in the status/text field.
I've walked this through into the backbone sync method and I see the $.ajax being built and everything looks fine. Has anyone run into this problem?
here is my code if it helps, this is a function that calls two .ashx services to first check for a file's existence then to open it. The part that isn't working for me is the "me.collection.fetch().
openDocument: function () {
var me = this,
fileId = me.model.get('id'),
userId = Dashboard.Data.Models.UserModel.get("UserInfo").User_ID,
fileRequest = '/genericHandlers/DownloadFile.ashx?id=' + fileId + '&userId=' + userId,
fileCheck = '/genericHandlers/CheckFileExistance.ashx?id=' + fileId + '&userId=' + userId;
//hide tooltip
me.hideButtonTooltips();
// Check for file existance
$.ajax({
url: fileCheck
})
.done(function (data) {
if (data && data === "true") {
document.location.href = fileRequest;
me.collection.fetch();
} else if (!!data && data === "false") {
"This file is no longer available.".notify('error');
}
})
.fail(function (data) {
"Something went wrong during the File Existance check".notify('error');
"Something went wrong during the File Existance check".log(userId, 'error', 'Docs');
});
},
my collection:
// docsCollection.js - The collection of ALL the documents available to a given user
// Document Collection
Dashboard.Collections.DocsCollection = Backbone.Collection.extend({
model: Dashboard.Models.DocumentUploadModel,
url: function () {
return 'apps/docs/Docs/' + this.userId;
},
initialize: function (options) {
this.userId = options.userId;
this.deferredFetch = this.fetch();
},
comparator: function (model) {
return -(new Date(model.get('expirationDate')));
},
getDaysSinceViewedDocuments: function () {
return this.filter(function (model) {
return model.get('daysSinceViewed') !== null;
});
},
getNewDocuments: function () {
return this.filter(function (model) {
return model.get('isNew');
});
},
getExpiredDocuments: function () {
return this.filter(function (model) {
return model.get('isExpired');
});
}
});
and my model:
Dashboard.Models.DocumentUploadModel = Backbone.Model.extend({
defaults: {
fileArray: [],
name: '',
description: '',
accesses: [],
tags: [],
expirationDate: ''
},
initialize: function () {
this.set({
userId: Dashboard.Data.Models.UserModel.get("UserInfo").User_ID,
expirationDate: (this.isNew()) ? buildExpirationDate() : this.get('expirationDate')
}, { silent: true });
function buildExpirationDate() {
var date = new Date((new Date()).getTime() + 24 * 60 * 60 * 1000 * 7),
dateString = "{0}/{1}/{2}".format(date.getMonth() + 1, date.getDate(), date.getFullYear());
return dateString;
}
},
firstFile: function () {
return this.get('fileArray')[0];
},
validate: function (attributes) {
var errors = [];
if (attributes.name === '' || attributes.name.length === 0)
errors.push({
input: 'input.txtName',
message: "You must enter a name."
});
if (attributes.description === '' || attributes.description.length === 0)
errors.push({
input: 'textarea.taDescription',
message: "You must enter a description."
});
if (errors.length > 0)
return errors;
return;
},
sync: function (method, model, options) {
var formData = new FormData(),
files = model.get("fileArray"),
$progress = $('progress'),
success = options.success,
error = options.error;
// Nothing other than create or update right now
if (method !== "create" && method !== "update")
return;
// Build formData object
formData.append("name", model.get("name"));
formData.append("description", model.get("description"));
formData.append("accesses", model.get("accesses"));
formData.append("tags", model.get("tags"));
formData.append("expirationDate", model.get("expirationDate"));
formData.append("userId", model.get("userId"));
formData.append("isNew", model.isNew());
// if not new then capture id
if (!model.isNew())
formData.append('id', model.id);
for (var i = 0; i < files.length; i++) {
formData.append('file', files[i]);
}
xhr = new XMLHttpRequest();
xhr.open('POST', '/genericHandlers/UploadDocsFile.ashx');
xhr.onload = function () {
if (xhr.status === 200) {
if (success)
success();
} else {
if (error)
error();
}
}
if ($progress.length > 0) {
xhr.upload.onprogress = function (evt) {
var complete;
if (evt.lengthComputable) {
// Do the division but if you cant put 0
complete = (evt.loaded / evt.total * 100 | 0);
$progress[0].value = $progress[0].innerHTML = complete;
}
}
}
xhr.send(formData);
},
upload: function (changedAttrs, options) {
this.save("create", changedAttrs, options);
}
});
You're assigning a value to document.location.href before you try to fetch your collection:
document.location.href = fileRequest;
me.collection.fetch();
Changing document.location.href will change the whole page and in the process, any currently running JavaScript will get shutdown so I wouldn't expect your me.collection.fetch() to ever get executed.

Resources