JavaScript Form validation in IE - javascript

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.

Related

MVC 5 - Validate a specific field on client-side

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

Custom Verify.js validation rule not applying

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;

Ignoring autocomplete='off' in chrome browser [duplicate]

When using the xhtml1-transitional.dtd doctype, collecting a credit card number with the following HTML
<input type="text" id="cardNumber" name="cardNumber" autocomplete='off'/>
will flag a warning on the W3C validator:
there is no attribute "autocomplete".
Is there a standards-compliant way to disable browser auto-complete on sensitive fields in a form?
Here is a good article from the MDC which explains the problems (and solutions) to form autocompletion.
Microsoft has published something similar here, as well.
To be honest, if this is something important to your users, 'breaking' standards in this way seems appropriate. For example, Amazon uses the 'autocomplete' attribute quite a bit, and it seems to work well.
If you want to remove the warning entirely, you can use JavaScript to apply the attribute to browsers that support it (IE and Firefox are the important browsers) using someForm.setAttribute( "autocomplete", "off" ); someFormElm.setAttribute( "autocomplete", "off" );
Finally, if your site is using HTTPS, IE automatically turns off autocompletion (as do some other browsers, as far as I know).
Update
As this answer still gets quite a few upvotes, I just wanted to point out that in HTML5, you can use the 'autocomplete' attribute on your form element. See the documentation on W3C for it.
I would be very surprised if W3C would have proposed a way that would work with (X)HTML4. The autocomplete feature is entirely browser-based, and was introduced during the last years (well after the HTML4 standard was written).
Wouldn't be surprised if HTML5 would have one, though.
Edit: As I thought, HTML5 does have that feature. To define your page as HTML5, use the following doctype (i.e: put this as the very first text in your source code). Note that not all browsers support this standard, as it's still in draft-form.
<!DOCTYPE html>
HTML 4: No
HTML 5: Yes
The autocomplete attribute is an enumerated attribute. The attribute
has two states. The on keyword maps to the on state, and the off
keyword maps to the off state. The attribute may also be omitted. The
missing value default is the on state. The off state indicates that by
default, form controls in the form will have their autofill field name
set to off; the on state indicates that by default, form controls in
the form will have their autofill field name set to "on".
Reference: W3
No, but browser auto-complete is often triggered by the field having the same name attribute as fields that were previously filled out. If you could rig up a clever way to have a randomized field name, autocomplete wouldn't be able to pull any previously entered values for the field.
If you were to give an input field a name like "email_<?= randomNumber() ?>", and then have the script that receives this data loop through the POST or GET variables looking for something matching the pattern "email_[some number]", you could pull this off, and this would have (practically) guaranteed success, regardless of browser.
No, a good article is here in Mozila Wiki.
I would continue to use the invalid attribute. I think this is where pragmatism should win over validating.
How about setting it with JavaScript?
var e = document.getElementById('cardNumber');
e.autocomplete = 'off'; // Maybe should be false
It's not perfect, but your HTML will be valid.
I suggest catching all 4 types of input:
$('form,input,select,textarea').attr("autocomplete", "off");
Reference:
http://www.w3.org/Submission/web-forms2/#the-autocomplete
http://dev.w3.org/html5/markup/input.html
If you use jQuery, you can do something like that :
$(document).ready(function(){$("input.autocompleteOff").attr("autocomplete","off");});
and use the autocompleteOff class where you want :
<input type="text" name="fieldName" id="fieldId" class="firstCSSClass otherCSSClass autocompleteOff" />
If you want ALL your input to be autocomplete=off, you can simply use that :
$(document).ready(function(){$("input").attr("autocomplete","off");});
Another way - which will also help with security is to call the input box something different every time you display it: just like a captha. That way, the session can read the one-time only input and Auto-Complete has nothing to go on.
Just a point regarding rmeador's question of whether you should be interfering with the browser experience: We develop Contact Management & CRM systems, and when you are typing other people's data into a form you don't want it constantly suggesting your own details.
This works for our needs, but then we have the luxury of telling users to get a decent browser:)
autocomplete='off'
autocomplete="off" this should fix the issue for all modern browsers.
<form name="form1" id="form1" method="post" autocomplete="off"
action="http://www.example.com/form.cgi">
[...]
</form>
In current versions of Gecko browsers, the autocomplete attribute works perfectly. For earlier versions, going back to Netscape 6.2, it worked with the exception for forms with "Address" and "Name"
Update
In some cases, the browser will keep suggesting autocompletion values even if the autocomplete attribute is set to off. This unexpected behavior can be quite puzzling for developers. The trick to really forcing the no-autocompletion is to assign a random string to the attribute, for example:
autocomplete="nope"
Since this random value is not a valid one, the browser will give up.
Documetation
Using a random 'name' attribute works for me.
I reset the name attribute when sending the form so you can still access it by name when the form is sent. (using the id attribute to store the name)
Note that there's some confusion about location of the autocomplete attribute. It can be applied either to the whole FORM tag or to individual INPUT tags, and this wasn't really standardized before HTML5 (that explicitly allows both locations). Older docs most notably this Mozilla article only mentions FORM tag. At the same time some security scanners will only look for autocomplete in INPUT tag and complain if it's missing (even if it is in the parent FORM). A more detailed analysis of this mess is posted here: Confusion over AUTOCOMPLETE=OFF attributes in HTML forms.
Not ideal, but you could change the id and name of the textbox each time you render it - you'd have to track it server side too so you could get the data out.
Not sure if this will work or not, was just a thought.
I think there's a simpler way.
Create a hidden input with a random name (via javascript) and set the username to that. Repeat with the password. This way your backend script knows exactly what the appropriate field name is, while keeping autocomplete in the dark.
I'm probably wrong, but it's just an idea.
if (document.getElementsByTagName) {
var inputElements = document.getElementsByTagName("input");
for (i=0; inputElements[i]; i++) {
if (inputElements[i].className && (inputElements[i].className.indexOf("disableAutoComplete") != -1)) {
inputElements[i].setAttribute("autocomplete","off");
}
}
}
I MADE THIS WORK IN 2020!
I basically create a css class that applies -webkit-text-security to my inputs.
Here's the link to a more recent discussion:
https://stackoverflow.com/a/64471795/8754782
This solution works with me:
$('form,input,select,textarea').attr("autocomplete", "nope");
if you want use autofill in this region: add autocomplete="false" in element
ex:
<input id="search" name="search" type="text" placeholder="Name or Code" autcomplete="false">
Valid autocomplete off
<script type="text/javascript">
/* <![CDATA[ */
document.write('<input type="text" id="cardNumber" name="cardNumber" autocom'+'plete="off"/>');
/* ]]> */
</script>

Pointing to first field after validation

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();

how to insert value in input, with javascript

So I tried to do something like this -
$('#price').val(price);
price is 300, and it shows good on browser, in input field, but when I want to take it out and mail it with PHP, in $_POST['price'] it doesn't show up, How can I insert something in inputs value with JavaScript, so I can mail it? It seems this is not an insertion in value, but just a feature to display something, correct?
Maybe this code can help you
document.getElementById('yorInputID').value = "Your Value";
There are a few possible reasons:
1) Your input field is not inside the form.
2) You are actually using a GET and not a POST.
Assuming that you can see the value updated in Firebug or Chrome's equivalent, it's gotta be one of those. Switch over to using $_REQUEST and see if that changes anything.
Your input for #price needs to also have a name "price"
<input id="price" value="price" />
From your question I'm assuming that this input is hidden -- and if that's the case I want to advise you not to rely on hidden fields + Javascript to provide you with security. It's so easily hackable I wouldn't even call it hacking.
Make sure the input is not "disabled" when the form submits.
if it's disabled the form don't send it.

Categories

Resources