JQuery Validator plugin validating conditions - javascript

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.

Related

How can i validate after pressing 4th digits of number before page submit using ajax and JavaScript?

I'm working on an existing postal code which is not saved it is a requirement. I have called ajax after pressing 4 digits using keyup function. My ajax is working fine but I'm not able to retrieve validation message I mean after ajax call the same code will be saved in the database.
//Trigger ajax event on sender address after 4th character typed.
$('#postalCode').on('keyup', function () {
if ($(this).val().length == 4) {
type: "get",
$.ajax({
url: "/masterController/checkPostalcode?ajax=true",
data: {
postalCode: $("#postalCode").val()
},
success: function (result) {
alert("user already exists");
//Now validate here show message postal code already exist. How?
},
error: function (response) {
$('#ErrorContainer').hide();
}
});
}
});
//This validation part
$("#subOfficeForm").validate({
rules: {
"postalCode": {
required: true,
minlength: 4,
maxlength: 4,
digits: true
},
"SubOffice": {
required: true,
minlength: 2
}
},
errorPlacement: function (error, element) {
if ((element.attr("name") == "postalCode")) {
$("#ReceiverErrorContainer").html(error);
$("#ReceiverErrorContainer").show();
}
else if ((element.attr("name") == "SubOffice")) {
$("#ErrorContainer").html(error);
$("#ErrorContainer").show();
}
//displays a tooltip
element.attr('title', error.text());
$(".error").tooltip({
position: {
my: "left+5 center",
at: "right center"
},
trigger: "hover"
});
},
//highlight the error field with red
highlight: function (element, error) {
$(element).css('background', '#FFCCCB');
},
// Called when the element is valid:
unhighlight: function (element) {
$(element).css('background', '#ffffff');
}
});
//And this is snapshots
Befor entering 4th digits
//And entering 4th digits
After entering 4th digests of postal code
There’s a few things wrong with this. It looks like the message is coming back from the server side, so something would need to be adjusted there. Also, JS lives client side and is only a suggestion (it can be manipulated and then people can write injection to your database), you must validate on the server side for security. You would want to use regex on both sides to ensure validation
[0-9]{4}
If I'm not mistaken, you need to check the validation result like this :
success: function (result) {
if(!result)
{
showErrorAlert('error message') ;
preventDefault();
}
else{
//submit data
}
},

How to make already exist email or username validation in semantic ui form?

Hi I am new in semantic ui framework and I want to make the validation like email already exist or username already exist .so what I am doing I have made a custom rule and run the ajax for checking email or username already exist or not.... Please check bellow code ex. of email already exist
email: {
identifier: 'email',
rules: [{
type: 'email',
prompt: 'Please enter a valid e-mail'
},
{
type: 'alreadyExistemail',
prompt: 'This email is already registered, please choose another one.'
}
]
}
$.fn.form.settings.rules.alreadyExistemail = function(param) {
return Check_existence(param);
}
function Check_existence(param) {
//Here I am running ajax which is communicating with db and returning true or false.
var a;
$.ajax({
method: "POST",
url: ajax_url,
async:false,
data: { 'action': 'checkEmailalreadyexist','email':param},
success: function (data) {
a = data;
}
});
return a;
}
But Problem is that Ajax is running with every single typed alphabet and I want (for specific field) it should first validated by other rule then custom rule functionality work. so is it possible I can check other rule valid in custom rule like that
$.fn.form.settings.rules.alreadyExistemail = function(param) {
if (is valid(email)) {
return Check_existence(param);
}
}
or can any one please suggest how can I make validation like email already exist or username already exist in semantic ui form?

jQuery required( dependency-expression ) is not working properly

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.

jquery validation submitbutton not working after corrected validation error

When using the jQuery validation plugin (http://docs.jquery.com/Plugins/Validation/validate):
I want the following behavior: Validate as soon as the user presses submit (instead of actually submitting I am using an ajax post request).
What happens though is the following: As soon as submit is pressed, validation runs, I get a validation error when applicable, then when I correct the mistake, and press submit the form gets re-validated, but when there are no validation errors, the ajax post is not made, only the form gets validated.
When there are no validation errors in first instance, the post is made instantly, like it should.
I have the following:
<script type="text/javascript">
$(document).ready(function(){
$("#form").validate({
onkeyup: false,
onclick: false,
onsubmit: true,
rules: {
telNR: {
required: true,
digits: true,
minlength: 10
}
},
messages: {
telNR: {
required: "Fill in a valid telephone NR",
minlength: "A telephoneNR is 10 characters long",
digits: "Use only numerics"
}
},
submitHandler: function(form) {
var jqxhr = $.post("sendMail.php", { telNR: $("#telNR").val() },
function(data) {
alert("Done");
})
.error(function(jqXHR){
alert("Error");
});
}
});
})
</script>
You may be having some ghost validation errors. Try adding the following to your options to cleanup the errors on focus of the form:
focusCleanup: true

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