jQuery required( dependency-expression ) is not working properly - javascript

I am using jquery validation plugin. When I was using required( dependency-expression ) i noticed that
required( dependency-expression ) are not working properly. as mentioned that i tried for
$("#flight_availability").validate({
rules: {
Trip: { required: true },
DepartDate: { required : "#OneTrip:checked" },
Origin: { required:"#OriginId:blank" }
},
});
In the above mentioned code the code DepartDate: { required : "#OneTrip:checked" }, works fine but Origin: { required:"#OriginId:blank" } does not work.
Whats wrong with the code? I used firebug. It did not show any errors. even used validation debug option too, but :(

As per OP's comments:
"even if OriginId is empty(blank), it validates it as true"
Yes, that is exactly how you programmed it.
Origin: {
required: "#OriginId:blank"
}
The above code is saying that the Origin field is only required when the #OriginId field is left blank. Using #OriginId:filled, this logic is saying that the Origin field must remain empty if the #OriginId is filled in. If that's not exactly correct, then you can use the :blank selector instead.
http://jsfiddle.net/xMAs5/
If you want the opposite behavior then use the :filled selector instead.
Origin: {
required: "#OriginId:filled"
}
http://jsfiddle.net/xMAs5/1/
Otherwise, here is a demo using a custom method called empty that works as per your comment: "So if OriginId is empty means Origin value (anything) is invalid."
$(document).ready(function () {
$.validator.addMethod('empty', function (value, element) {
return (value === '');
}, "This field must remain empty!");
$("#flight_availability").validate({
rules: {
Trip: {
required: true
},
DepartDate: {
required: "#OneTrip:checked"
},
Origin: {
empty: {
depends: function (element) {
return $("#OriginId").is(":blank")
}
}
}
}
});
});
DEMO: http://jsfiddle.net/Ab8bT/

It might be the jQuery puesdo selector try using :empty instead of :blank.

Related

JQuery form validations plugin regex (pattern method) problems

this is my first post ever on stack overflow!
I've been trying to use the jquery validator plugin to validate my register form on php without submitting it (i already have server-side validations). Well, i don't know much about js (for now) but i'm trying to use jquery validation from this plugin https://jqueryvalidation.org/
I'm also using the additional-methods.js (pattern included) which gives you more validation methods.
Let me explain my situation... I'm using regex on php to validate my html forms and it works like a charm. When i tried to use the same regex for jquery it'd throw and error (i already have some basic code js and it works).
I tried a lot of regex formats and nothing works, i don't know what i'm doing wrong. I also tried to escape the code and it doesn't throw errors but it still doesn't work.
I'm getting "invalid format" all the time and i can't seem to understand why is it not working.
All the regex formats i've found on the internet don't work, it's crazy, maybe you can help me.
This is the pattern i'm actually using to validate the nombre (name) input in php: /^\pL+(?>[ ']\pL+)*$/u
*Also I've copied the patterns method inside my local js and removed the additional-methods cdn from my .php but it's the same.
** Ignore the [A-Z] thingy, i've been trying a lot of things, none of them work :(
Here my local.js
$.validator.setDefaults({
errorClass: 'text-danger position-absolute ml-1',
highlight: function
(element) {
$(element)
.closest('.form-control')
.addClass('is-invalid');
},
unhighlight: function (element) {
$(element)
.closest('.form-control')
.removeClass('is-invalid');
},
errorPlacement: function (error, element) {
if (element.prop('type') === 'checkbox') {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
}
});
$.validator.addMethod("pattern", function (value, element, param) {
if (this.optional(element)) {
return true;
}
if (typeof param === "string") {
param = new RegExp("^(?:" + param + ")$");
}
return param.test(value);
}, "Invalid format.");
$("#reg_form").validate({
debug: true,
rules: {
nombre: {
required: true,
pattern: [A-Z]
},
apellido: {
required: true,
lettersonly: true
},
email: {
required: true,
email: true,
},
password: {
required: true,
strongPassword: true
},
cpassword: {
required: true,
equalTo: '#password'
}
},
messages: {
nombre: {
required: 'Requerido',
pattern: 'Formato inválido',
max: 'Muy largo'
},
apellido: {
required: 'Requerido',
pattern: 'Formato inválido',
max: 'Muy largo'
},
email: {
required: 'Please enter an email address.',
email: 'Por favor ingresa un email <em>válido</em>.',
},
password: {
required: true
}
}
});
You may have a minor oversight, change your pattern implementation to -
nombre: {
required: true,
pattern: "^[A-z\s]+$"
},
your pattern needs to be a string for it to be implemented. Secondly while \pL does work well to get any letter form any language, but not all programming languages have it implemented. (look here for what you can do in java script) You are better off just adding in the few extra letters you expect to encounter in the regex.

Skip validation of model attribute using Backbone.Validation

I have a view that is rendered dynamically. It may have some inputs or may not have.
After a user fills everything and tries to send data I call this.model.isValid(true) ( or this.model.isValid() ) and it returns false even if the data from inputs is valid.
I think the cause is Backbone Validation tries to validate attributes of inputs we did not render.
Is there any solution to skip model attributes if we have no sticked elements of a view?
UPDATE:
My model is similar to this:
MyApp.module("RecordModel", function (RecordModel, MyApp, Backbone) {
RecordModel.recordModel = Backbone.Model.extend({
validation: {
inn: {
pattern: 'inn',
msg: MyApp.messages.inn
},
bik: {
pattern: 'bik',
msg: MyApp.messages.bik
},
uin: {
pattern: 'uin',
msg: MyApp.messages.uin
},
sum: {
pattern: 'sum',
msg: MyApp.messages.sum
}
}
});
});
Bindings:
bindings: {
'#uin': {
observe: 'uin',
setOptions: {
validate: true
},
events: MyApp.Validation.events.inputEvents
},
'#bik': {
observe: 'bik',
setOptions: {
validate: true
},
events: MyApp.Validation.events.inputEvents
},
'#inn': {
observe: 'inn',
setOptions: {
validate: true
},
events: ParkingMate.Validation.events.inputEvents
},
'#sum': {
observe: 'sum',
setOptions: {
validate: true
},
events: MyApp.Validation.events.inputEvents
}
}
So for some reason we din't render #sum input for instance. As we haven't it got in our DOM, it doesn't exists in RecordModel, but backbone still tries to validate it. Or if we have this input in our DOM, everything works fine.
How can I allow empty values but still validate if the user enters something?
By default, if you configure a validator for an attribute, it is
considered required. However, if you want to allow empty values and
still validate when something is entered, add required: false in
addition to other validators.
validation: {
value: {
min: 1,
required: false
}
}
If you can't let empty values (like at creation), Backbone.validation overrides isValid adding features to the default behavior. What's interesting is the array parameter we can pass:
// Check if name and age are valid
var isValid = model.isValid(['name', 'age']);
With this, we can then validate only the fields that exist within the model at the moment:
model.isValid(_.keys(model.attributes));

formvalidation.io form validation. If "other", please explain

I'm using the FormValidation plugin in Bootstrap and am loving it, except I can't figure out one thing. I have a form with an "other" check box. If you check "other", I want an explanation typed into another field. I've been all over the website (formvalidation.io), but I'm not finding an answer. Unfortunately, I know just enough JS to be dangerous.
Here's the code for the validator I'm using on the check boxes.
'work_type[]': {
validators: {
choice: {
min: 1,
message: 'Please choose at least one work type.'
}
}
}
There's another field called "other_work" that I would like to require a string in if work_type has a value of "Other Work".
For anyone trying to figure this out check out callback functions
You declare your own function something like this:
function optionOtherValidator(value) {
if ($('#amountOther input').is(':checked');) {
return /^\w+$/.test(value);
}
return true;
},
Then in your fields array you declare it as a callback:
fields: {
optionOther: {
validators: {
callback: {
message: 'Please specify a value for other',
callback: optionOtherValidator
}
}
}
...

Changing box color using jQuery on email validation?

I have an input box which tests whether the email in the box is a valid one. This is the script:
$("#myform").validate({
rules: {
field: {
required: true,
email: true
}
}
});
This tests for the email. I also have this script which would change the color by adding another class to the form.
$("#myform").toggleClass("othercolor");
Im just not sure where to put this code. Sorry for the newby question just new to jQuery. Thanks =D
Here's a demo... (UPDATED)
It looks like you might be using the jQuery validation plugin. Assuming that you are, you just need to initialise the form validation by executing $("#myform").validate() when the page loads (e.g. by putting it calling it from $(document).ready()).
$(document).ready(function(){
$("#myform").validate();
});
​
If you want to apply a CSS class when the focus leaves the email field, you could do something like this:
var validator = null;
$(document).ready(function(){
validator = $("#myform").validate({
rules: {
cemail: {
required: true,
email: true
}
}
});
$("#cemail").blur(function() {
if (validator.form()) {
$("#myform").addClass("othercolor");
}
else {
$("#myform").removeClass("othercolor");
}
});
});​
​
validator.form() returns true if the form is valid, and false if it isn't. Note that .toggleclass() won't do what you want here; you'll need to add or remove the class based on the return value of validator.form().
why dont you add it into the success callback in jQuery:
$("#myform").validate({
rules: {
field: {
required: true,
email: true
}
},
success: function(){
$(this).toggleClass('red');
}
});

get JSON with functions from server

I use JQuery Validate to validate forms on my webapp. I can pass JQuery Validate a list of rules to use to validate my form like this:
$("#myform").validate({
rules: {
age: {
required: true,
min: 3
},
parent: {
required: function(element) {
return $("#age").val() < 13;
}
}
}
});
Now I would like to generate those validation rules on the server instead of coding them in my JavaScript, do an $.ajax request to get them, attach them to the form and be all set.
But this
{
rules: {
age: {
required: true,
min: 3
},
parent: {
required: function(element) {
return $("#age").val() < 13;
}
}
}
}
is not valid JSON, because there is the function declaration. Is there a way to do this?
To elaborate: my application is made of static HTML and JS, and my only interaction with the server is with some REST services that return JSON.
So when I get a person from the server because I want to edit it in a form, I do
$.ajax({url: '/person/1',
success: function(data) {
/* fill form fields */
...
/* get validation rules from server and attach to form
something like */
$.ajax({url: '/person/validation_rules',
success: function(rules) {
/* something like */
$('#myform').validate(rules);
}
}
});
Thanks.
How about simply returning it as a JS literal, instead of as JSON?
Edit:
Your original description included:
{
rules: {
age: {
required: true,
min: 3
},
parent: {
required: function(element) {
return $("#age").val() < 13;
}
}
}
}
That's a JS literal, not a JSON string, and is completely valid to return from the server, in and of itself. No additional changes necessary, and the function declaration is just fine. JSON is simply a subset of the JS literal. (http://www.json.org/js.html).
So, you could easily return that structure from your server, via some AJAX request, exactly as it is.
For more details: http://snook.ca/archives/javascript/json_is_a_subse
If you are already generating Javascript on the server, you don't need to load it as JSON. If you are loading this function from http://myserver.com/validation.js, instead of calling it with ajax, just call it from the script tag, eg.
<script src="http://myserver.com/validation.js"></script>
You will also need to edit slightly generated code:
var validationRule = {
rules: {
age: {
required: true,
min: 3
},
parent: {
required: function(element) {
return $("#age").val() < 13;
}
}
}
}
then your validation will look like
$("#myform").validate(validationRule);
EDIT: if server response must be JSON, you can get it as a string and eval() it. or you can arrange some valid json which you can tweak to desired form, say:
{
...
"minParentAge": 13
}
and then construct function from it.
Create a single global variable as your root namespace - just like third party libraries like jQuery do. Call it for instance MyNamespace.
Then load js files that populate this namespace, that way you get a minimal DOM footprint.
My preferred way is doing it like this:
<myFunctions.js>
MyNamespace = window.MyNamespace || {};
(function(){
function utilityFunction1() {
//....
}
function utilityFunction2() {
//....
}
MyNamespace.UtilityFunctions = {
utilityFunction1: utilityFunction1,
utilityFunction2: utilityFunction2
};
})();
</myFunctions.js>
then include it like always
<script src="myFunctions.js" type="text/javascript"></script>

Categories

Resources