I m trying to validate to validate the input depends on other html element.
If the other html is empty it should validate the input and if not the not valid.
This is my HTML:
<input id="oka_rijkregister_last" name="oka_rijksregisternummer_last" type="text">
<span id="oka_rijkregister_last_BtnVal" class="error_msg"></span>
I have a separate function on input which validate the input data, if data is not correct it displays the error message in span element else remains empty.
Here is my JS code which i am trying to validate depends on span element.
$("#myform").validate({
rules: {
oka_rijksregisternummer_last : {
minlength: {
param:17,
depends: function (element) {
if($("#oka_rijkregister_last_BtnVal").html() === "") {
return true;
}
else {
return false;
}
}
}
}
}
});
My code is working till param 17 and rest it ignores.
Can anyone help with this?
Thanks in advance.
I am using the Unobtrusive Jquery for ClientSideValidation,Which is working correctly,
I want to do some enhancement if Possible....!!
How could I show an Alert Box that "something is missing" in a
Page?
How could I focus on the error TextBox, Checkbox or any
Other control?
Any suggestion would be Helpful...!!
For 2), you can use custom JavaScript code like this:
$("selector for error messages, e.g. class name")[0].scrollIntoView().focus();
OR
document.querySelector("same selector").scrollIntoView().focus();
First method scrolls the page to your element with error, second focuses on that element.
Suppose you have one input box for email
<input type="text" name="" class="" id='emailId' placeholder="" />
document.getElementById("emailId").focus();
if you have more than one input box you can try like this
var myIds = ['id1', 'id1', 'id1', 'id1', 'id1']
for (var i in myIds) { fuction doValidation(myIds[i]) {} }
function getId(id) {
return document.getElementById(id);
}
fuction doValidation(myIds[i]) {
if (getId(myIds[i]).value == 'your error check') {
getId(myIds[i].focus();
return false
}
}
}
$("input[type='submit']").click(
function(event) {
event.preventDefault(); // Do not actually submit
alert("You entered " + $("#your-name-id").val() + ", age " + $("#your-age-id").val());
});
Currently working on input file error validation When i searched about the validation i have found jquery validation so i have started using it and again when i searched about how to validate the input file i have got some useful information from SO Based on that I have created error validation page for input file. With my current code I can able to upload pdf & Jpeg file and view the file but the validation was not happening if user click next button without uploading any file it should say you have 2 files missed if the user upload one file and he click next button it should say you have 1 file miss. I have tried giving required in the html input type field and tried giving required in jquery validation nothing was working.
Here is my jquery code
$(".attachForm").validate({
ignore: false,
onkeyup: false,
showErrors: function (errorMap, errorList) {
var errors = this.numberOfInvalids();
if (errors) {
var message = errors === 0 ? 'You missed 1 field. It has been highlighted' : 'You have missed ' + errors + ' fields. Please fill before submitted.';
$("#error_message").html(message);
$(".error_msge").show();
} else {
$(".error_msge").hide();
}
this.defaultShowErrors();
},
errorPlacement: function () {
return false;
},
highlight: function (element) {
if($('input').attr('type') == 'checkbox') {
} else {
$(element).addClass('errRed');
$(".file_ipt").addClass('errRed');
}
$(element).prevAll('label').find('span.required-star').addClass('text-error-red').removeClass('text-error-black');
},
unhighlight: function (element) {
if($('input').attr('type') == 'checkbox') {
} else {
$(element).removeClass('errRed');
$(".file_ipt").addClass('errRed');
}
$(element).prevAll('label').find('span.required-star').addClass('text-error-black').removeClass('text-error-red');
},rules: {
apt_code:"required",
apt_cer:"required",
checkfile:"required"
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
I tried changing the name in all field but no use
Here is the fiddle link for the detailed code
Kindly please suggest me. kindly guide as i am not getting any stuff :(
Thanks for looking the question.
You have to assign the unique name attribute to each <input type="file" class="checkfile">
<input type="file" class="checkfile" name="file_alpha">
<input type="file" class="checkfile" name="file_beta">
and then in rules you have to define both fields and make sure they are required
rules: {
file_alpha: {
checkfile: "required",
required: true,
},
file_beta: {
checkfile: "required",
required: true,
}
},
Fiddle
Correct Solution
Above solution will work because assigning the unique name and required rules set will trigger the validation but will not return the desired result because OP trying to validate the input with same name attribute and triggering the error counter according to number of invalid input fields.
Reason the validation not working in original code because no required rules
rules: {
checkfile:"required"
},
defined anywhere.
so work around is set required rules and add to inputs with same name attribute OR type using jQuery each() function
$("input[type=file]").each(function() {
$(this).rules("add", {
required: true,
});
});
and validation will work, errors will triggered with counter and on validating the input field, error counter decrease as like OP's desired output.
Fiddle Proper Working Example
I searched and can't figure out how to validate the new reCaptcha, before form submit, along with the validate function of jQuery validation Plugin.
My intent:
$.validator.addMethod('reCaptchaMethod', function (value, element, param) {
if (grecaptcha.getResponse() == ''){
return false;
} else {
// I would like also to check server side if the recaptcha response is good
return true
}
}, 'You must complete the antispam verification');
$("#form").validate({
rules: {
name: {
required: true,
minlength: 2
},
email: {
required: true,
email: true
},
reCaptcha: {
reCaptchaMethod: true
}
},
messages: {
name: "Please fill your name",
email: "Please use a valid email address"
},
submitHandler : function () {
$.ajax({
type : "POST",
url : "sendmail.php",
data : $('#form').serialize(),
success : function (data) {
$('#message').html(data);
}
});
}
});
In a few words: I would like to check server-side, with the remote method, if the user has passed the recaptcha validation BEFORE submitting the form, along with other rules of validation.
I'm able to check the recaptcha AFTER submission (on sendmail.php), but it would be nicer to have the recaptcha validation response along with other fields validation.
The main reason is for a better user experience, having all fields checked at once.
I've managed to achieve this, moving the check inside the submitHandler:
submitHandler : function () {
if (grecaptcha.getResponse() == ''){
// if error I post a message in a div
$( '#reCaptchaError' ).html( '<p>Please verify youare human</p>' );
} else {
$.ajax({
type : "POST",
url : "sendmail.php",
data : $('#form').serialize(),
success : function (data) {
$('#message').html(data);
}
});
}
}
But I don't like this approach, for 2 reasons:
It is just checking if the recaptcha has been filled, not if it's valid, and
User feels like it is a 2 step verification.
In this answer they say it can be done rendering the Recaptcha on a callback, to specify a function call on a successful CAPTCHA response.
I tried to implement that, but I've not been able to use this solution within a rule of the validate() function.
I know this question is a bit dated but I was having the same problem and just found the solution.
You can do this by adding a hidden field next to the reCaptcha div, like:
<div class="g-recaptcha" data-sitekey="{YOUR-SITE-KEY-HERE}"></div>
<input type="hidden" class="hiddenRecaptcha required" name="hiddenRecaptcha" id="hiddenRecaptcha">
then in your javascript:
$("#form").validate({
ignore: ".ignore",
rules: {
name: {
required: true,
minlength: 2
},
email: {
required: true,
email: true
},
hiddenRecaptcha: {
required: function () {
if (grecaptcha.getResponse() == '') {
return true;
} else {
return false;
}
}
}
},(...rest of your code)
NOTICE THAT YOU MUST HAVE the ignore: ".ignore" in your code because jquery.validate ignores hidden fields by default, not validating them.
If you want to remove the error message on reCapcha validate add a data-callback to the reCapcha element
<div class="g-recaptcha" data-sitekey="{YOUR-SITE-KEY-HERE}" data-callback="recaptchaCallback"></div>
And then in your js file add
function recaptchaCallback() {
$('#hiddenRecaptcha').valid();
};
You can also prevent the form submit in the submitHandler
$("#loginForm").validate({
rules: {
username: {
required: true,
minlength: 6
},
password: {
required: true,
},
},
submitHandler: function(form) {
if (grecaptcha.getResponse()) {
form.submit();
} else {
alert('Please confirm captcha to proceed')
}
}
});
I've found your solution to be interesting (#FabioG).
But, I've modified it for use a bit by myself and I'm willing to share the code for others to use.
I was working on an interactive form, that validated as you completed steps.
It was used for ordering food. Ergo, the form required verification and activation of the register button and it is using the latest reCaptcha to date (5/12/2016).
Also, this code handles expired reCaptcha, server-side verification via ajax (though not included - if someone needs it to feel free to comment on my answer and I'll edit it accordingly).
Let's get started.
The HTML code:
<form id="registerForm" method="get" action="">
<fieldset class="step-1">
<h4>Step One:</h4>
<span class="clock">Register under one minute!</span>
<label for="email-register" class="label">E-mail*</label>
<input id="email-register" name="email-register" type="email" value="" autocomplete="off"/>
<label for="password-register" class="label">Password*</label>
<input id="password-register" name="password-register" type="password" value="" autocomplete="off"/>
<div class="g-recaptcha" data-sitekey="6LeS4O8SAAAAALWqAVWnlcB6TDeIjDDAqoWuoyo9" data-callback="recaptchaCallback" data-expired-callback="recaptchaExpired" style="margin-top: 3rem;"></div>
<input id="hidden-grecaptcha" name="hidden-grecaptcha" type="text" style="opacity: 0; position: absolute; top: 0; left: 0; height: 1px; width: 1px;"/>
</div>
</fieldset>
<fieldset class="step-2">
<h4>Step two:</h4>
<span class="notice">All fields with a sign are required!*</span>
<label for="first-name" class="label">First Name*</label>
<input name="first-name" id="first-name" type="text" value="" />
<label for="last-name" class="label">Last Name*</label>
<input name="last-name" id="last-name" type="text" value="" />
<label for="address" class="label">Address*</label>
<input name="address" id="address" type="text" value=""/>
<label for="entrance" class="label">Entrance</label>
<input name="entrance" id="entrance" type="text" value=""/>
<label for="apartment-number" class="label">Apartment #</label>
<input name="apartment-number" id="apartment-number" type="text" value="" />
<label for="inter-phone" class="label">Interphone</label>
<input name="inter-phone" id="inter-phone" type="text" value=""/>
<label for="telephone" class="label">Mobile Number*</label>
<input name="telephone" id="telephone" type="text" value="" />
<label for="special-instructions" class="label">Special Instructions</label>
<textarea name="special-instructions" id="special-instructions"></textarea>
<div>
</fieldset>
<button class="button-register" disabled>Register</button>
</form>
So as you can see, the button for submission (".button-register") is initially disabled.
You can only enable it by filling the mandatory (*) fields.
Please, keep in mind that I didn't include any CSS. The form is on a bare minimum and is just for educational purposes.
Few things that differ from #FabioG, the answer is:
There is no need to hide the element or use the ".ignore". I've hidden it with inline CSS.
There is a response callback for successful reCaptcha and expired reCaptcha.
So, if your reCaptcha expires while filling out the form it will make it invalid and the button will be disabled again.
As well, the form uses an input field (the hidden input field) to pass the information onto AJAX(PHP later on) and verify it server-side (It is a potential security risk, I covered it more at the end of the text).
Let's move on to JavaScript/jQuery.
JavaScript/jQuery:
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
function recaptchaCallback() {
var response = grecaptcha.getResponse(),
$button = jQuery(".button-register");
jQuery("#hidden-grecaptcha").val(response);
console.log(jQuery("#registerForm").valid());
if (jQuery("#registerForm").valid()) {
$button.attr("disabled", false);
}
else {
$button.attr("disabled", "disabled");
}
}
function recaptchaExpired() {
var $button = jQuery(".button-register");
jQuery("#hidden-grecaptcha").val("");
var $button = jQuery(".button-register");
if (jQuery("#registerForm").valid()) {
$button.attr("disabled", false);
}
else {
$button.attr("disabled", "disabled");
}
}
function submitRegister() {
//ajax stuff
}
(function ($, root, undefined) {
$(function () {
'use strict';
jQuery("#registerForm").find("input").on("keyup", debounce(function() {
var $button = jQuery(".button-register");
if (jQuery("#registerForm").valid()) {
$button.attr("disabled", false);
}
else {
$button.attr("disabled", "disabled");
}
}, 1000));
jQuery("#registerForm").validate({
rules: {
"email-register": {
required: true,
email: true
},
"password-register": {
required: true,
minlength: "6"
},
"first-name": "required",
"last-name": "required",
address: "required",
telephone: "required",
"hidden-grecaptcha": {
required: true,
minlength: "255"
}
},
messages: {
"email-register": "Enter valid e-mail address",
"password-register": {
required: "Enter valid password",
minlength: "Password must be bigger then 6 chars!"
},
"first-name": "Required!",
"last-name": "Required!",
address: "Required!",
telephone: "Required!"
},
submitHandler: submitRegister
});
});
})(jQuery, this);
As you can see here, there are a few functions: recaptchaCallback() and recaptchaExpired().
recaptchaCallback() that is embeded via the data attribute data-callback, uses the grecaptcha.getResponse() to see if the reCaptcha is validated, if so it enters the token to the hidden input field and asks for re-validation via the jQuery("#registerForm).validate();.
However, if the reCaptcha expires in the meanwhile it will use the assigned function in the "data-expired-callback", to remove the token from the input field and ask for re-validation again which will fail because the field is empty. This is achieved with the function recaptchaExpired().
Later in the code, you can see that we added a jQuery keyup function, to check for re-validation and see if the user has passed on the required information to the input fields. If the information and the field validate successfully the keyup function will enable the Register button.
Also, I've used a debounce script (tnx, David Walsh) on keyup. So it doesn't cause browser lag. Since, there would be a lot of typing.
But, keep in mind if a user decides to circumvent the reCaptcha he can always just enter the "255" character long string to the input field. But, I've gone a step further and made an AJAX verification server-side to confirm the reCaptcha. Though, I haven't included it in the answer.
I think this code is a marginal improvement on the previous answer. If you have any questions or need the AJAX/PHP code feel free to comment. I'll supply it when I can.
Heres the codepen as well: reCaptcha with jQuery.validation
You can find all the information regarding the reCatpcha data-attributes and functions in their API here: reCaptcha API
Hope it helped someone!
Regards,
I struggled with this one today and ended up going with:
<form onsubmit="return $(this).valid() && grecaptcha.getResponse() != ''">
Which just feels like the simplest way to do it. Someone is bound to complain about putting js inline like that but I'm ok with it.
I have just started with JavaScript and want to validate a form. All the tutorials I've found create an alert for feedback, but I'd like to use onblur and give an error message next to the field. I managed to do the two functions separately but can't merge them. I'd really appreciate your help!
This is what I came up with, but it doesn't do what I need:
function validateFirstName()
{
var x=document.forms["demo"]["firstname"].value;
if (x==null || x=="" || x==)
{
function addMessage(id, text)
{
var textNode = document.createTextNode(text);
var element = document.getElementById(id);
element.appendChild(textNode);
document.getElementById('firstname').value= ('Firstname must be filled out')
}
return false;
}
}
So the following is a simple way to validate a form field by checking the value of an input when the form is submitted. In this example the error messages are just sent to the div element about the form but this should still help you out.
The HTML code looks something like this:
<div id="errors"></div>
<form onSubmit="return validate(this);">
<input type="text" name="firstName" placeholder="What's your first name?">
<button type="submit" value="submit">Submit</button>
</form>
The Javascript code looks something like this:
function validate(form) {
var errors ='';
if(form.firstName.value =="") {
errors += '<li>Please enter your first name</li>';
}
if(errors !='') { //Check if there are any errors, if there are, then continue
var message = document.getElementById("errors"); //assigns the element with the id of "errors" to the variable "message"
message.innerHTML = "<ul>" + errors + "</ul>"; //adds the error message into a list with the error message into the HTML
return false;
} else {
return true;
}
}
Once you understand this you should be able to figure the rest out on your own or go to http://www.w3schools.com/ and check out the javascript section to help you out.
I'm not sure what you really looking for. If I understood right (and I can be very wrong) you are looking for something like:
var x = undefined; // Can be undefined, null, or empty string
if (x==null || x=="" || x==undefined) { // do no forget to check for undefined
function addMessage(id, text) {
// Your validation code goes here
alert(id + text);
};
addMessage(1234, "Mandatory field!");
}
Note, there are several ways to do it. I just showing the simplest way I can think of...