jQuery Validate Plugin - Trigger validation of single field - javascript

I've got a form that can optionally be pre-populated via facebook connect. Once a user connects, their name and email are automatically filled in. The problem is that this doesn't trigger the remote validation to check if the email already exists.
Is there a way I could call the validation on that field alone? Something like:
$('#email-field-only').validate()
would be idea. Searched through the docs with no luck.

This method seems to do what you want:
$('#email-field-only').valid();
Edit
API has changed, see Paul's answer.

Use Validator.element():
Validates a single element, returns true if it is valid, false
otherwise.
Here is the example shown in the API:
var validator = $( "#myform" ).validate();
validator.element( "#myselect" );
.valid() validates the entire form, as others have pointed out. The API says:
Checks whether the selected form is valid or whether all selected
elements are valid.

$("#FormId").validate().element('#FieldId');

For some reason, some of the other methods don't work until the field has been focused/blured/changed, or a submit has been attempted... this works for me.
$("#formid").data('validator').element('#element').valid();
Had to dig through the jquery.validate script to find it...

If you want to validate individual form field, but don't want for UI to be triggered and display any validation errors, you may consider to use Validator.check() method which returns if given field passes validation or not.
Here is example
var validator = $("#form").data('validator');
if(validator.check('#element')){
/*field is valid*/
}else{
/*field is not valid (but no errors will be displayed)*/
}

When you set up your validation, you should be saving the validator object. you can use this to validate individual fields.
<script type="text/javascript">
var _validator;
$(function () {
_validator = $("#form").validate();
});
function doSomething() {
_validator.element($('#someElement'));
}
</script>
-- cross posted with this similar question

in case u wanna do the validation for "some elements" (not all element) on your form.You can use this method:
$('input[name="element-one"], input[name="element-two"], input[name="element-three"]').valid();
Hope it help everybody :)
EDITED

$("#element").validate().valid()

Related

fill articlenumber automatically after writing articlename

I have a HTML <form> and im creating it with php. It contains three <input> fields.
The second <input> field should be filled automatically, when the first one is filled. A HTTP request is triggered over an API. The request works fine and puts out the article number. I tested it already.
The problem is, that it has to run the request and fill the field, whenever the other field is filled.
I have tried it with jQuery:
<script>
$(document).ready(function(){
$("input[name*='artNr1']").click(function(){
.get("artikelnamen_suchen.php", nummeruebergeben($_POST['artName1']));
});
});
<script>
Any help is appreciated.
Form screenshot
I think you forgot to insert the $ (dollar sign) before .get()
Your code should be like this :
<script>
$(document).ready(function(){
$("input[name*='artNr1']").click(function(){
$.get("artikelnamen_suchen.php", nummeruebergeben($_POST['artName1']));
});
});
<script>
jquery provides the change() method to listen to change events, e.g. on <input> fields. You can replace the click() handler with it.
$("input[name*='artNr1']").change(function(){
$.get("artikelnamen_suchen.php", nummeruebergeben($_POST['artName1']));
});
The problem with your code is, that you call jquery.get() with the PHP variable $_POST['artName1']. This shows two flaws:
If the replacement with that PHP value works, it is evaluated on server side and therefore never replaced with the current value from the <input>, that is present on client side
You seem to expect the value to be transferred via POST, but you use jquery.get() to transfer it via GET.
To address the first flaw, you need to use the value from the first <input> instead of the value that was evaluated from PHP.
$("input[name*='artNr1']").change(function(){
var articleNumber = $(this).val();
//TODO: $.get("artikelnamen_suchen.php", nummeruebergeben($_POST['artName1']));
});
Because you are currently in the onChange handler of the first <input> field, it is available as the this context in that function. With jquery.val() you can access its current value.
To address the second flaw, you can use two different ways. Either use the jquery.post()mehtod to send your data as POST to PHP:
$("input[name*='artNr1']").change(function(){
var articleNumber = $(this).val();
$.post("artikelnamen_suchen.php", {
'artName1': articleNumber
}).success(function(result){
//Work with the result here
});
});
Or provide the information as GET and access it in PHP as a $_GET field instead of $_POST:
In javascript:
$("input[name*='artNr1']").change(function(){
var articleNumber = $(this).val();
$.get("artikelnamen_suchen.php?artName1=" + articleNumber)
.success(function(result){
//Work with the result here
});
});
In php
$articleNumber = $_GET['artName1'];
... //Use $articleName instead of $_POST['artName1'] in your PHP code.
After that you can work with result to replace the value in your second input. But thats another question... :-D

AngularJS: Function to test if has class

On a form submit trying to run a function in a controller that checks for matching passwords and if email field contains a class.
Scenerios:
If the passwords don't match it fails
If email contains ng-invalid it fails
Passwords validate just fine, the issue is trying to see if the Email field contains a class after form submit.
In jQuery would write:
if($(#email).hasClass('ng-invalid'){//email is invalid man return false;}
But in Angular not using jQuery. Tried several ways in vanilla JS to see if #email has class 'ng-invalid' but it's not working. JavaScript Check If Element Has Class
The end result is using the function "formValidate()" in Jasmine unit test to verify if formValidate() is true or false.
Basic Implementation:
PLUNKER
Jasmine (This should fail):
it('Join Now button should be enabled when form fields are valid.',
function(){
var ctrl = createController();
$httpBackend.flush();
var joinNowBtn = registrationEl.find('.join-now-btn');
$rootScope.user = {
'email': 'hola#friend.c',
'password': 'abc',
'passwordConfirm': 'abc'
};
expect($rootScope.formValidate()).toBeTruthy(); //THIS TEST SHOULD FAIL
//expect submit button to not have a disabled attribute
});
You don't need to check for ng-invalid class. Just check if $scope.registration_form.email.$invalid is true or false.
$scope.user.email.$invalid didn't work because $scope.user.email is just a string.
Form validation information is put into $scope.formName. You can use the following:
$scope.formName.$invalid === true
$scope.formName.fieldName.$invalid === true
Check NgModelController docs.
You can use hasClass()
Angular natively has access to jqLite's hasClass().
http://docs.angularjs.org/api/angular.element
You shouldn't need to be checking classes a la jQuery. You can check the validity of the form input by passing the form into your submit function and checking to see if email.$invalid is true or false. So something like this:
html
ng-submit="submitForm(this.registration_form)"
js function
$scope.formValidate = function(form){
if(form.email.$invalid){
alert('email is invaid')
return;
}
// etc.
}

Blank Field Tracking

I am trying to track the fields that are left blank on my website form when it is submitted.
The form I am using is used by my sales agents, and since I do not immediately see the submitted info before the sales agent has a chance to modify the submitted information, I am looking to see if they are filling out all of the info on the site instead of adding in more info later in the CRM. This will help me to optimize the form for their use. Currently the form is written using HTML, PHP, jQuery and AJAX.
I have not tried anything yet, as I do not even know where to begin with this. I have not seen it done before.
Let me know if you need to see the markup or if this question needs more clarification. Feel free to point me in the direction of a tutorial if that is easiest.
Thanks for the help!
That is what PHP empty() is for:
if (empty(trim($_POST['some_field']))
{
// Nothing was supplied.
}
So, you could create an array of 'required' fields like this:
$required = array('this', 'that', 'the', 'other');
...and then loop through them:
$errors = false;
foreach ($required as $field)
{
$field_value = isset($_POST[$field]) ? trim($_POST[$field]) : null;
if (empty($field_value))
{
$errors[] = 'The "' . $field . '" field was not submitted.';
}
}
if ($errors)
{
// Do something now that you know there are missing fields.
// Here, we're sending an email...
$subject = 'These fields were not filled out';
$body = 'The following errors occurred: ' . implode(', ', $errors);
mail('email#example.com', $subject, $body);
}
I think that you want to know the way how to check and validate the form information before submit. And as you said that you use jQuery, so I advise that there are 2 solutions to solve the problem at least.
1, write the validate script by yourself.
you can use the following script to check the form data before submit.
jQuery(form).submit(function(){
// Here you can validate your form data
// and if the data are incorrect,
// you can return false, and the form submission will be cancelled
});
2, use the jQuery Validation plugin.
The plugin can be got from http://jqueryvalidation.org/, and you can import it with the following script.
<script type="text/script" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/jquery.validate.js"></script>
And then, you only need to add some special attribute in your form.
For example, if you add "required" of your input field, which means the field must be filled with the characters.
<form>
<input type="text" name="username" required />
</form>
And then, write the following script to notify the plugin to validate the form before submission.
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("form").validate();
});
</script>
You can check in both PHP or JS. If you want to do this server side so you can save this information simply check the POST results of the form.
if (trim($_POST['myField'])=="") {
//not filled out. if you have default values, check for it in the if above too.
mail('your#email.com', 'Subject', 'Your body.');
}

custom jquery validation and unobtrusive JavaScript

I'm trying to write a custom validation that gives an error if html exists in the textarea when they submit a form.
I have the following -
its not working and I'm not sure why.
also I don't understand the unobtrusive part
can someone show me how to do that as I am seeing other examples on SO that have it.
text area has a class"note"
the form is called "noteform"
<script type="text/javascript" >
$(document).ready(function () {
$.validator.addMethod('nohtml', function (value, element) {
var text = $(".note").text();
if ($(text).length > 0) {
return false;
}
else {
return true;
}
}, 'Html not allowed');
// // **not sure what to do here**
// $.validator.unobtrusive.adapters.add('containsnohtml', {}, function (options) {
// options.rules['nohtml'] = false;
// options.messages['nohtml'] = options.message;
// });
$('#noteform').validate({
rules: { nohtml: "required nohtml" }
});
});
</script>
There's a couple issues here. One is you're trying to mix unobtrusive and regular jquery validation. If you want to use validate like this then you need to make sure jquery.validate.unobtrusive.js is NOT included. This is because jquery.validate.unobtrusive.js automatically parses and produces a validator for the document and the very first thing that validate does is check if there's an existing validator and exits if there is.
If you do decide to go the non-unobtrusive route, be sure not to use the $.validator.unobtrusive.adapters.add since it will cause an error without jquery.validate.unobtrusive.js.
I would recommend going with unobtrusive validation though since I think you're using MVC3.
If you're going to go with unobtrusive validation you have two choices, set the data-* attributes yourself by adding data-val="true" data-val-nohtml="Html not allowed" to your textarea as suggested by JohnnyO and including a span with data-valmsg-for="note" data-valmsg-replace="true" to show the error message. Or you can make your own DataAnnotation attribute.
Here's the code for the addMethod (needed for both kinds of validation)
<script type="text/javascript">
(function ($) {
$.validator.addMethod('nohtml', function (value, element) {
// Test 'value' for html here. 'value' is the value of the control being validated.
return true; // Return true or false depending on if it passes or fails validation, respectively.
}, 'Html not allowed');
} (jQuery));
</script>
and the javascript needed for the unobtrusive is as follows
$.validator.unobtrusive.adapters.addBool('nohtml');
Regarding how to make a custom validation attribute, since I'm not sure what language you're using, assuming you're using MVC3, or if you even need this info anymore 4 months after you asked, I'm going to simply leave these links for reference.
A brief comparision of Traditional vs Unobtrusive JavaScript Validation in MVC 3 - Mitchell Trent's Blog
ASP.NET MVC 3 Custom Validation - Microsoft Developer Network
Although I haven't tested this, I think all you're missing is to wire up the element that you want to validate with the nohtml rule. Something like this:
$('textarea.note').rules('add', {
nothml: true
});
Based on some of your description, I assume you're using ASP.NET MVC3. In that case, you would only need to use the unobtrusive adapter if you're generating the validation attributes server side on your html element (e.g. <textarea data-val="true" data-val-nohtml="Html not allowed"></textarea>). In such a case, you'll need the unobtrusive adapter to wire up the element to use your nohtml rule.

using reCAPTCHA with ajax....javascript loading problem

I trying to implement reCAPTCHA in one of my forms,...but i am using ajax as the submission. (More specifically the prototype ajax.updater)
Once I submit and error check my form I try to load the reCAPCHTA widget thingy (in my updated div element) which basically just calls a javascript file like so:
<script type="text/javascript" src="http://api.recaptcha.net/challenge?k=6Le6SwUAAAAAAIWm8wCRFd8SrI-H0R1Yx4Tkw2Ks"></script>
However the JS file is not being read?...and i've tried all combination of evalScripts:true and evalJS:'force' etc. in the ajax.updater.....however i don't think I have a very good understanding of why the js file isn't processing :(
If anyone can shed some light on this issue I will be very appreciative.
Thanks, Andrew
This doesn't address your exact problem, but 'Dark Side of the Carton' has some excellent code for validating reCAPTCHA via jQuery AJAX which might help.
In summary:
Add the following Javascript:
$(function() {
function validateCaptcha() {
var challengeField = $('input#recaptcha_challenge_field').val(),
responseField = $('input#recaptcha_response_field').val();
// alert(challengeField);
// alert(responseField);
// return false;
var html = $.ajax({
type: 'POST',
url: 'ajax.recaptcha.php',
data: "recaptcha_challenge_field=" + challengeField + "&recaptcha_response_field=" + responseField,
async: false
}).responseText;
if (html.replace(/^\s+|\s+$/, '') == "success") {
$('#captchaStatus').html(' ');
// Uncomment the following line in your application
return true;
} else {
$('#captchaStatus').html(
'Your captcha is incorrect. Please try again'
);
Recaptcha.reload();
return false;
}
}
// Modified as per comments in site to handle event unobtrusively
$('#signup').submit(function() {
return validateCaptcha();
});
});
Then add the ajax.recaptcha.php file which: "outputs only the word “success” if the captcha matches and a message and the response from reCaptchta if it fails. This is important because we are looking for the word success in our validateCaptcha() function."
require_once('/inc/recaptchalib.php');
$publickey = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX'; // you got this from the signup page
$privatekey = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$resp = recaptcha_check_answer(
$privatekey,
$_SERVER['REMOTE_ADDR'],
$_POST['recaptcha_challenge_field'],
$_POST['recaptcha_response_field']
);
if ($resp->is_valid) {
?>success< ?
} else {
die(
"The reCAPTCHA wasn't entered correctly. Go back and try it again." .
"(reCAPTCHA said: " . $resp->error . ")"
);
}
The example is in PHP, but I adapted it easily to work with Zope/Python
Be careful using any sort of client-side script, such as JavaScript, for validation. You have no control over the end-user's browser. The purpose of a CAPTCHA is to prevent automated submissions of a form. Anyone sophisticated enough to set that up isn't going to have a problem overriding your JavaScript validation and CAPTCHA checking. For example, they could set validateCaptcha() to always return true, bypassing your careful checks - or just disable JavaScript.
That being said, there's nothing wrong with performing the entire form submission with ajax and using the results of the CAPTCHA check to determine if the form gets processed or not.
The important point is that the decision of whether or not to handle the form has to be made on the server-side, not the client-side.
Why client-side validation is not enough
to answer my own question...
there is a reCAPTCHA AJAX api....which is pretty easy way to get around this problem:
link text
Also,..the documentation on the http://www.prototypejs.org/api/ajax/updater site.....talks about the evalscript option and how is only puts any javascript through the native eval() function....which kind of screws me over trying to implement error checking with WMD...but that's another story.
Andrew
If that's the literal code snippet you're using, you haven't closed the tag... so it wouldn't be evaluated.
call Recaptcha.reload(); on callback event in your Ajax code., it will reload new Recapcha every time that Ajax submitted
Hi Friend i found the answer
https://developers.google.com/recaptcha/docs/display?hl=es#AJAX
And in this how validate
http://blog.reaccionestudio.com/comprobar-recaptcha-con-ajax-usando-jquery/
Success for you
Securing AJAX calls with reCaptcha
function performAJAX() {
let captcha = $('[name=g-recaptcha-response]');
$.ajax({
url: 'ajaxHandler.html',
data: {
captcha: (captcha.length?captcha[0].value:''),
// other data fields
},
});
}
I have had similar issues with getting reCaptcha to play nicely when loaded into the page using jQuery's .load() method. Here is a page that has a novel solution: http://www.maweki.de/wp/2011/08/recaptcha-inside-a-with-jquery-ajax-or-load-dynamically-loaded-object/
Basically the reCaptcha API uses document.write method to display the reCaptcha. When you get jQuery invloved this won't work. Use this PHP code in place of loading recaptcha.js
<?php
$api = file_get_contents('http://www.google.com/recaptcha/api/js/recaptcha_ajax.js');
$api = str_replace('document.write','$("body").append',$api);
echo $api;
?>
It just does a find for document.write and replaces it with $(selector).append.
Made my implementation work.

Categories

Resources