Validation groups for Backbone.Validation - javascript

I have a Backbone model, say User, and I want to reuse it in a Sign Up page and in a Change settings page.. In the Sign Up page I have a form with two fields: email and password both required, while in the Change Settings page there is another form with email and name (but not the password field), the first required the second one not..
Using the Backbone.Validation plugin I have something like this for the validation process:
var User = Backbone.Model.extend({
validation: {
name: {
rangeLength: [0, 100]
}
email: {
required: true
pattern: "email"
rangeLength: [1, 100]
}
password: {
required: true
rangeLength: [8, 100]
}
} // validation
} // User
It works well for the Sign Up form, but it doesn't work in the Change Settings form since the password is missing.
Is there a way for reusing the same validation on two different forms as in my case? Something like validation groups, one group for sign up's fields and another one for settings's field (where I could exclude the password)?..

I have an idea if you're using the backbone.validator by thedersen v0.8.2 and above.
But it will pollute the model a little bit by introducing a flag attribute, which using to determine which kind of validation you need.
var User = Backbone.Model.extend({
validation: function() {
var validationCriteria = {
name: {
rangeLength: [0, 100]
}
email: {
required: true
pattern: "email"
rangeLength: [1, 100]
}
password: {
required: true
rangeLength: [8, 100]
}
}
switch (this.attributes.validationMode) {
case 'signup':
// do nothing since we need all validation. just to demonstare, if just two modes can just simple if statement
break;
case 'changeSetting':
delete validationCriteria.password;
break;
default:
break;
}
return validationCriteria; // validation
} // User
});
var user = new User({
validationMode: 'signup'
}) //when initiate the model in signup view
var user = new User({
validationMode: 'changeSetting'
}) //when initiate the model in change setting view

Related

How to add this UK registration validation to jquery?

In this project I have the following jquery code to validate a form. It works fine, but i'd like it to be more specific by implementing a more thorough validation for UK reg plates.
My javascript code is:
function ValidateSspcpForm()
{
$('#SspcpForm').validate({
rules: {
'sspcp[reg]': {
required: true,
rangelength: [2, 8],
},
messages: {
'sspcp[reg]': {
required: "Your car's registration is required in advance, Please input one here.",
rangelength: "The registration number must be between 2 and 7 characters in length"
},
}
});
}
The method I want to implement is this, it seems to cover everything for UK plates which is perfect for my use case:
(^[A-Z]{2}[0-9]{2}\s?[A-Z]{3}$)|(^[A-Z][0-9]{1,3}[A-Z]{3}$)|(^[A-Z]{3}[0-9]{1,3}[A-Z]$)|(^[0-9]{1,4}[A-Z]{1,2}$)|(^[0-9]{1,3}[A-Z]{1,3}$)|(^[A-Z]{1,2}[0-9]{1,4}$)|(^[A-Z]{1,3}[0-9]{1,3}$)
Any help or ideas would be much appreciated!
Found it. Definitely appears to be quite simple. I'm new to JavaScript, so wasn't aware it would let you outside of the validate method. For anyone else searching, this is how you would implement UK registration plate validation with jquery.validate:
function ValidateSspcpForm()
{
$.validator.addMethod('Registration', function(value){
return /^(^[A-Z]{2}[0-9]{2}\s?[A-Z]{3}$)|(^[A-Z][0-9]{1,3}[A-Z]{3}$)|(^[A-Z]{3}[0-9]{1,3}[A-Z]$)|(^[0-9]{1,4}[A-Z]{1,2}$)|(^[0-9]{1,3}[A-Z]{1,3}$)|(^[A-Z]{1,2}[0-9]{1,4}$)|(^[A-Z]{1,3}[0-9]{1,3}$)|(^[A-Z]{1,3}[0-9]{1,4}$)|(^[0-9]{3}[DX]{1}[0-9]{3}$)/.test(value);
}, 'reg validation has failed');
$('#SspcpForm').validate({
rules: {
'sspcp[reg]': {
required: true,
rangelength: [2, 8],
Registration: true
},
},
messages: {
'sspcp[reg]': {
required: "Your car's registration is required in advance, Please input one here.",
Registration: "This registration number is not a recognised UK plate"
},
}
});
}

How to make Input->value->type->search dynamic?

Usually a regular person's name does not contain numbers, so I added this search property to prevent numbers with RegEx to my Input element:
type: new sap.ui.model.type.String({}, { search: "^[^0-9]+$" })
But numbers should be allowed for a company's name. So how can I make this search value dynamic?
To visualize it:
"dwd3" should be invalid when it's anything other than "Company"
"dwd3" should be valid when it's a "Company"
Here's my minimal example - what I've tried so far is commented out, since it didn't work (resulted in numbers being valid at all times).
// Set data model
let data = {
"salutation": "Company",
"name": ""
};
let oModel = new sap.ui.model.json.JSONModel();
oModel.setData(data);
// Create page
let oPage = new sap.m.VBox();
oPage.setModel(oModel);
// Add salutation input
oPage.addItem(
new sap.m.Input({
value: {
path: "/salutation"
}
})
);
// Add name input
oPage.addItem(
new sap.m.Input({
value: {
type: new sap.ui.model.type.String({}, {
minLength: 2,
maxLength: 40,
search: "^[^0-9]+$"
/* not working...
search: {
parts: [
"/salutation",
],
formatter: (salutation) =>
salutation === "Company" ? "^.*$" : "^[^0-9]+$"
}
*/
}),
path: "/name",
},
required: true,
})
);
// Attach validation handlers
sap.ui.getCore().attachValidationError(function(oEvent) {
oEvent.getParameter("element").setValueState(sap.ui.core.ValueState.Error);
});
sap.ui.getCore().attachValidationSuccess(function(oEvent) {
oEvent.getParameter("element").setValueState(sap.ui.core.ValueState.None);
});
// Insert page
oPage.placeAt("content");
<script id='sap-ui-bootstrap' type='text/javascript' src='https://sapui5.hana.ondemand.com/resources/sap-ui-core.js' data-sap-ui-libs="sap.m,sap.ui.commons,sap.ui.table" data-sap-ui-theme="sap_bluecrystal">
</script>
<body class='sapUiBody'>
<div id='content'></div>
</body>
If the validation rule of one field depends on the value of another field, you could use events like change (with or without valueLiveUpdate=true) for validation.
A type should be something that does not depend on external life.
Another thing you could do is reacting on change event of your salutation field and exchange the type of the input field for the name (depending on the value of salutation)
PS: (edit) to be hontest, I wouldn't restrict a name field to anything that it may or may not contain. Depending on the country specific laws you may be allowed to use digits...

jQuery validation - validate sections as well as globally in a page

I have a page similar to the below given diagram,
The page has multiple sections (User Information, Account Information etc;) as well as common controls (like subject textbox, date textbox etc)
When the user clicks on Add button in user information section, it has to validate the associated controls
When the user clicks on the Submit button in the top, the subject textbox and the table should be validated for required data.
How can I achieve this?
I am able to validate the user section but not sure how to proceed with global validation on the page.
TypeScript:
class Validation {
static FormTrackingId = '#FormTracking';
private static ApplyRules() {
$(Component.SelectId).rules("add", {
required: true,
messages: {
required: "Name is required."
}
});
$(Component.TextBoxNumberId).rules("add", {
required: true,
messages: {
required: "Number is required."
}
});
$(Component.TextAreaNotesId).rules("add", {
maxlength: 10,
messages: {
maxlength: jQuery.validator.format("The maximum allowed length of note(s) is {0} characters.")
}
});
}
public static IsValid(): boolean{
$(Validation.FormTrackingId).validate();
Validation.ApplyRules();
return $(Validation.FormTrackingId).valid();
}
}
Any suggestion on how to handle this scenario will be greatly appreciated. Thanks.

JQuery Validator plugin validating conditions

I am having a few issues validating my data fully with the validator plugin.
I have 2 fields; fieldOne and fieldTwo. I then have 2 PHP files, process.php and processfailed.php.
Now I have quite a few conditions.
If fieldOne and fieldTwo are both empty, I want the error to display to the user but no PHP file called.
If one of the fields has valid data, and the other has invalid data or is empty, I want it to call process.php (I dont want a validation error event to occur).
Only if both fields have invalid data do I want processfailed.php to be called, from within the validation error event.
The code I have so far is this (removed some sections to shorten it)
var validator = $("#my_form").validate({
rules: {
fieldOne: {
require_from_group: [1, '.datagroup'],
maxlength: 40
},
fieldTwo: {
require_from_group: [1, '.datagroup'],
minlength: 8
}
},
groups: {
datagroup: "fieldOne fieldTwo"
},
submitHandler: function (form) {
$.ajax({
type: "POST",
url: "process.php",
data: {
'fieldOne': $("#fieldOne").val(),
'fieldTwo': $("#fieldTwo").val()
}
})
return false;
},
invalidHandler: function (form, validator) {
/* Submit the form even if validation fails: */
$.ajax({
type: "POST",
url: "processfailed.php",
data: {
'fieldOne': $("#fieldOne").val(),
'fieldTwo': $("#fieldTwo").val()
}
})
return false;
}
});
In regards to them both being empty, at the moment it displays the error to the user, but it also appears to be calling processfailed.php as well (I dont want any php file called in this situation).
If I give valid data to one field and leave the other empty, this seems to work.
If I give valid data to one field and give invalid data to the other, this seems to call processfailed.php when it should call process.php (as long as one field is valid that is ok).
If I give invalid data to both fields (they both fail validation) the processfailed.php seems to be called as it should be.
So how can I handle both fields being empty (not to call any php file) and if one field is valid and the other invalid to call process.php and not processfailed.php.
Any advice appreciated.
For the first condition where both fields are empty, you can just place an if-statement in the invalidHandler method.
In order to not apply the validation to one of the fields when the other is valid, you could use the depends property of the rules.
$("#my_form").validate({
rules: {
fieldOne: {
require_from_group: [1, '.datagroup'],
maxlength: {
param: 2,
depends: function(element) {
var valTwo = $('#fieldTwo').val();
return !valTwo || (valTwo.length < 8);
}
}
},
fieldTwo: {
require_from_group: [1, '.datagroup'],
minlength: {
param: 8,
depends: function(element) {
var valOne = $('#fieldOne').val();
return !valOne || (valOne.length > 2);
}
}
}
},
submitHandler: function (form) {
alert("process");
return false;
},
invalidHandler: function (event, validator) {
if ($('#fieldOne').val() || $('#fieldTwo').val()) {
alert('processfailed');
} else {
alert('empty');
}
return false;
}
});
jsfiddle
I removed the groups property because it causes all messages to get displayed next to the first field, which doesn't seem correct when the message is because the second field violates the minlength rule.
Note: The first parameter to the invalidHandler function is the event object, not the form element, but you can get the form element using event.target.

Select method is not validated dynamically

I am using a select method in form and when I click on submit method without filing the form, various errors are shown which I have included in validate methods, like first name required, email required, etc.
So the problem is when I start entering the first name, the error disappears. But the same is not happening in case of select method. When I select certain options there, the error still remains saying, select at least one option. This error goes away when I click submit button. But I want this error to go away when I select at least one option, like in the case of first name when I start typing, the error goes away.
I have included my validation methods in $(document).ready(function()
Any help will be appreciated.
The following is the code snippet:
var newusercontainer = $('#newUsererrorcontainer');
var newuservalidator = $("#newUserForm").validate({
submitHandler: function(form) {
registerUser();
},
errorContainer: newusercontainer,
errorLabelContainer: $("ul", newusercontainer),
wrapper: 'li',
meta: "validate",
rules: {
newUserFirstName: {
required:true,
maxlength:50,
},
sector: {
required: true,
},
},
messages: {
newUserFirstName: {
required: "The First name field is required.",
maxlength: "Please enter with in 60 characters"
},
sector: {
required: "The Sector field is required.",
},
}
});

Categories

Resources