I'm using a new plugin to validate form fields called Verify.js, everything has been working great, until I started trying to create my own custom validation rules.
Here is the link to their documentation, where it explains how to create custom validations: http://verifyjs.com/#custom-rules
Even more helpful, is this example posted on JSfiddle by the plugin author: http://jsfiddle.net/jpillora/R4t84/1/ I copied the code format here almost precisely, yet it still doesn't work.
Right now, I am trying to get the form to not submit if the user has not selected the input field #YesExact. It is a very simple form validation, just trying to get this to work so I get the hang of writing custom validation rules with Verify.js
The HTML markup for the form field is like this:
p class="regular-content option-label">Do you know the exact size of your order?</p>
<input name="YesExact" id="YesExact" data-validate="checkExact" type="button" class="btn btn-tca padding-button" value="Yes">
The javascript I wrote that has the custom validation rule is written like this:
// custom form validation
$.verify.addRules({
checkExact: function (r) {
if ($('#YesExact').val() === "") {
$('#YesExact').notify("Please tell us you know the exact amount!", "error");
return "Please tell us you know the exact amount!" false;
}
return true;
}
});
This looks like it should totally work, I followed the example very closely. However, I have one major clue as to why it doesn't work... the javascript console says:
verify.js: Missing rule: checkExact
So how am I supposed to fix this? Where Verify.js can find the rule?
The webpage is HERE if you want to go check it out for yourself.
Thanks in advance for your help.
You have a syntax error at:
return "Please tell us you know the exact amount!" false;
change to return false;
You should also make sure to only set its value when clicked, as well as the "No" button, and then check if either are set, otherwise your validation will always return true. Though a better way in my opinion would be to have their clicks trigger the setting of a hidden field to either true or false which you could easily pull as a boolean server side.
I fixed this problem by including the verify.js script at the bottom of the file just before the closing body tag, assuming that your jquery file is also included before these below statements, and assuming that inputs are properly enclosed in <form> tag
<script src="js/Verfify.js" type="text/javascript"></script>
<script src="../yourFolder/yourJavascriptFileWithVerifyRules.js">
</body>
Also your return statement is wrong
return "Please tell us you know the exact amount!" false;
should be
return false;
Related
I building an eCommerce website for a client. However anyone with a good idea about jQuery/JS should be able to help as this does not relate to the backend.
They want to show a 'hidden' shop page, when a generic password is entered.
So on the homepage of the site will be a password field, and a submit button.
The password is generic, let's say 'letmein'. When entered, the link to the shop page should become active.
If possible it would also be great to have the link greyed out/disabled before the correct word is typed.
Is this possible? Thanks so much if anyone can help!
If passwords do matter and there is sensitive data behind this door you are creating, this is a terrible idea. Passwords should never be a front-end data, because they are accessible to anyone with computer. If user access really doesn't matter and this is just a superficial gateway to make users feel special, JavaScript is indeed the answer. If access is casual and security doesn't actually matter you should try this:
You could create a link that stays inactive until the right password is entered into an HTML <input>. Use JavaScript/jQuery to check if the password is correct and change the anchor's value if it is.
Something like this maybe:
HTML:
Password Invalid
<input type="text" id="password-field" />
JS:
var correctPass = "letmein"; // any password you want
$("#password-field").on("change", function() { // everytime the value changes we check the input for the password
if ($(this).val() == correctPass) { // if the value of the input is the password (no submit needed)
$("#link-to-site").attr("href", "www.actual-site-link.com"); // changes link of anchor
$("#link-to-site").html("You're in!"); // changes anchor's text to show a visual change (a nice UX touch)
}
});
Here's a working fiddle: JSFiddle
You can add the href after the password is correct and remove if it isn't like this here is working fiddle
As long as security doesn't matter this is just a link that you want to open up to everyone with no backend validation then this will work fine.
function updateLink(input) {
if (input.value == "letmein") {
document.getElementById("atag").href = "http://www.google.com";
} else {
document.getElementById("atag").removeAttribute("href");
}
}
<html>
<body>
<input type="text" onkeyup="updateLink(this);">
<a id="atag">Google</a>
</body>
</html>
However anyone with a good idea about jQuery/JS should be able to help as this does not relate to the backend.
Doing this on the front end is a bad idea. Anyone with a rudimentary knowledge of scripting will be able to enable the link (even without typing in the "password")
Thanks for your answers all.
To answer this question - no, security is not an issue here. It is just to add a layer of exclusivity. Users will receive the generic password when they sign up for the mailing list.
I want to populate a city/state drop down list based on the postal code a user types into a textbox. So when the text changes, I'm going to make an ajax call to retrieve the data. However, I only want to perform that ajax request for valid postal codes. The field already validates using the DataAnnotations.RegularExpression attribute and jquery.validate.unobtrusive validation library. I'm unclear on what can and can't be used from jquery.validate when using unobtrusive. I've looked at the unobtrusive code, but haven't gotten an understanding of it yet. So two questions:
Using javascript,
is there a way to force validation on a specific field, not the whole form?
is there a way to check whether a specific field is valid?
After digging around in the source code, I've come to these conclusions. First, the purpose of unobtrusive is to wire up the rules and messages, defined as data- attributes on the form elements by MVC, to jQuery.validation. It's for configuring/wiring up validation, not a complete wrapper around it, so when it comes to performing validation that is already set up, you don't have to worry about "circumventing", or not involving, unobtrusive.
So to answer the questions:
Yes, there are two ways. The Validator.element(element) function and the $.fn.valid() extension method. .valid actually calls Validator.element internally. The difference is .valid works on a jQuery which allows you to perform the validation on one or more fields (or the form itself). Validator.element performs validation on only a single element and requires you to have an instance of the validator object. Although the documentation states .validate() "validates the selected form", it actually appears to initialize validation for the form, and if it has already been called, it simply returns the validator for the form. So here are examples of two ways to validate an input (below #2).
Yes, but not without also performing the validation. Both of the methods from #1 return a boolean so you can use them to determine whether a field is valid. Unfortunately there doesn't appear to be anything exposed by the library that allows you to check the validation without, in effect, showing or hiding the validation message. You would have to get at and run the rule(s) for the field from your code, which may be possible, but my need didn't justify spending the time on it.
Example:
<form>
<input id="txtDemo" type="text"></input>
</form>
...
<script type="text/javascript">
$("#txtDemo").valid();
//or
//Get the form however it makes sense (probably not like this)
var validator = $("form").validate();
//Note: while .element can accept a selector,
//it will only work on the first item matching the selector.
validator.element("#txtDemo");
</script>
you can find if a single field is valid and trigger this validation this way:
$("#myform").validate().element("#elem1");
details here http://docs.jquery.com/Plugins/Validation/Validator/element#element
Use like this:
$('#Create').on('click', function () {
var form = $('#test').closest('form');
$(form).validate();
if (!$(form).valid()) {
return
} else {
// Bide the data
}
});
Hope it works for you
I have a webpage which has check-boxes, input fields, dropdowns etc.,
Mandatory conditions are checked using javascript. If anyone fails to fill these fields and press next button validation errors popup.
Now what I want to achieve is when someone fails to enter information in the mandatory fields, the cursor should go to the first field which caused the error.
Can anyone suggest me how to do this?
Add a class (something like input-error) for every invalid field. Then use something like:
var errors = document.querySelectorAll(".input-error");
if (errors.length > 0) {
errors[0].focus();
}
Here's an example: http://jsfiddle.net/NtHzV/1/
It really all depends on the structure of your code, how you're validating, what you're actually doing with validation, and what your HTML is.
At the same time, if you're doing something similar to my example, you might as well keep track of the first input with an error, then focus() it at the end of validation. Something like this:
http://jsfiddle.net/NtHzV/2/
UPDATE:
Bergi pointed out that querySelector might as well be used (instead of querySelectorAll) because you're only looking for the first input with errors. So here's an update:
var error_input = input_area.querySelector(".input-error");
if (error_input !== null) {
error_input.focus();
}
http://jsfiddle.net/NtHzV/3/
Here's specs on querySelector: https://developer.mozilla.org/en-US/docs/DOM/element.querySelector - Note that < IE8 does not support it.
The use of ".input-error" is because that is the CSS class selector, and will find the first (if any) element in a specific area with the class "input-error".
This line will focus the page on the element you specify. You should be able to implement this into your validation checks to focus on the bad elements.
document.getElementById("ID_Of_bad_field").focus();
I have input field
<input type="text" name="vehicle_make[]" id="make1"/>
and i have help dropdown that updates this field if user choose to do so. I do it trough standard jquery code
$("#make1").val("value");
Problem is, since i use validate plugin to validate this field, if user click on validate before entering anything in that box, he will get notice that he needs to fill it, but then if he fills it trough dropdown, validate plugin will not detect it until user click on submit again.
I know i could call submit in function in which i process dropdown, but i think that it is not right solution, since i would need to check if validation is already done before doing that (since if it is not, it would start validation before i want it to start).
I also need to tie some other things to that field also, so i would like to know is there is a way in which i could write function so it always check if field is filled, even if user did not fill it directly.
Sorry if i didn't explain everything right, this is my first message here.
Try this
$("#make1").change(function(){
//do something there
});
I have found solution. First, i created js variable form_submitted, and added onclick event to submit button, to change value of variable form_submitted to yes. Then, i created function:
function update_validation(){
if(form_submitted == 'yes'){
$("#my_form").valid();
};
};
that i call when user do something that is not detected regularly with validate plugin. This function manually starts validation again, but only if it has been started before by clicking on submit.
Hi all I am working on a contact or phone book application. So currently I am working on searching for records. Now I have this form with certain elements/fields being required or mandatory while others are optional.
So I wrote a very simple javascript function to check if those required fields are missing or not. It works greate on firefox and chrome however not in IE.
It seems that the if clause is failing in my js in IE because wheather i enter the required fields or don't enter the required fields i get the alert message telling me to enter the rquired fields. Mind you this doesn't happen in firefox only IE. So I'll put some relevant code bits here for you to have a look hoping you can help me out here:
head
some css code
...
<script type="text/javascript">
function disp_confirm()
{
if (document.contractor_phonebook_form.Service.value == "" || document.....etc.)
{
javascript:alert('Please enter all necessary fields!');
return false;
}
else
{
return true;
}
}
</script>
end of head beginning of body
<form action='<?php $PHP_SELF; ?>' method='post' name="contractor_phonebook_form" target="_self" onSbumit="return disp_confirm()">
some of the form elements are autofilled from a database query using mysql and php to fill the form elements. while others are simple drop down menus.
<select name="Service">
... etc..
hopefully you have an idea of what i have here and why does IE always give me the alert message please fill in the required fields wheahter I ENTER OR DON'T ENTER any form fields..
thank you in advance again..
OKAY I found the answer to my problem... Most browsers would detect the value of the option fields automatically meaning what I originally had was this:
<select name ="Service">
<option>NOCC</option>
<option>HVAC</option>
....etc.
</select>
however IE was always getting null values since I didn't explicitly specify the value attribute to the element tag. So all I did was change my code from that on top to the following:
<select name="Service">
<option value="NOCC">NOCC</option>
<option value="HVAC">HVAC</option>
....etc..
</select>
and now works fine in IE. Strange enough most browsers are able to detect the value attribute by looking at the option tag display however IE requires that you specifically define the value attribute otherwise will look at it as blank or null. and that's why my if clause was failing in IE because i didn't specify the value attribute and hence it was always blank even when I did choose a value from the drop down menu it still saw it as blank.
thank you all for your help I definately benefited by learning something new from your posts like JQuery.
cheers
There is a nice jQuery cross browser solution and provides validation for email addresses, dates, other common functions. You can define a common div where your errors can be displayed.
I've used this with Asp.net and had little trouble adapting it to my needs. There are quite a few users here at SO that have used this solution.
You should be calling alert like a normal function, without writing javascript: first.
However, your problem is that IE implements the value property for select elements differently.
You need to check whether any of the options' selected property is true.
This is easiest to do using jQuery, like this:
if ($('#service').val() === ""
|| $('#somethingElse').val() === "") {
alert("Please enter all necessary fields.");
return false;
} else
return true;
You dont need to put javascript: before your alert(); function.