Process invalid input from form with jQuery - javascript

I have a form with an input such as
<td class="units_depth_form">
<input id="id_form-0-rain" name="form-0-rain" step="0.01" type="number" />
</td>
and I want to allow a user to enter units. For instance the form could expect values in inches, but I would allow a user to enter '20 cm', and when leaving the text box it would contain '7.87'.
To do this I have in the JavaScript part of the page the following jQuery code:
$(".units_temp_form input").focusout(function() {
// Convert and replace if valid double ending with 'cm'
and I added 'novalidate' at the end of the form tag. The problem is that $(this).val() is empty when the input is invalid. Is there another way to get to the user entered value?
Before anyone suggests the solution, removing the type='number' part would solve the problem but I'd prefer not to do this. This form is created in Django through a ModelForm, and it would involve a lot of hacking that would defeat the purpose of using Django in the first place.

That seems to be the way browsers behave when they find invalid data inside a type="number" input.
Perhaps your best option is to use <input type="text"/> and implement the up and down arrows yourself. There are several options around, I found one that looks nice and another that keeps going on mouse down.
If the form inputs must be created with type="number" because of Django, you can change that on the client as soon as the page loads:
$(document).ready(function() {
$(".units_temp_form input").each(function(){
if ($(this).attr('type') == "number") {
$(this).attr('type', 'text');
}
});
});

Related

How to set a input text (with no ID or name) value with a subsequent submit of that input text?

I have been trying already all kind of code snippets in Chrome Dev tools on this website:
http://kiwisdr.sk3w.se:8073/?#
This is a software defined radio running on a webserver.
I would like to use Javascript to set the frequency (and submit) so that I can change the frequency the receiver is currently tuned to.
Manually on the GUI the user can just type a frequency (with or without enter) and the new frequeny inside the input box will be tuned.
This is the HTLM part of the website containing the input (no ID or name, so I am not sure how to properly adress this):
<form id="id-freq-form" name="form_freq" action="#" onsubmit="freqset_complete(0); return false;">
<input class="id-freq-input w3-input w3-border w3-hover-shadow" style="padding:0 4px;max-width:74px" size="8" onkeydown="freq_keydown(event)" onkeyup="freqset_keyup(this, event)" type="text" value="" onchange="w3_input_change('undefined', 'undefined')">
</form>
I managed to set the frequency, but I am stuck on how to make it submit.
This is the code I used to set the frequency input box to a certain value (1234.50):
targetForm = document.forms['form_freq'];
targetForm.elements[0].value = '1234.50';
I already tried to trigger the keydown, keyup or change events using some snippets I found, but I am not sure I adress the right elements in the form with it.
All I want to do is to mimic a user entry by code :-)
Could someone point me into the right direction by having a look on the way how the input works on this website and how I can make the website update the currently received frequency with javascript?
Thanks.
Short answer:
freqset_keyup(document.forms[1][0], null)
Nicer answer:
function change_freq(new_freq) {
var form = document.forms['form_freq'];
var freq_input = form.elements[0];
freq_input.value = new_freq;
freqset_keyup(freq_input, null);
}
change_freq(1234.50)

Can I get <input type=text> to look like <input type=password>?

I'm trying to deal with a frustrating Internet Explorer issue that prevents me from using jquery-validate in conjunction with jquery-placeholder. In short, the validation does not work on fields with type=password.
More info Here
One possible fix I came up with is to modify my passwords to be type=text, but this of course displays the passwords in plain-text rather than as *******.
Is there any clever html/js/css trick to make text fields display as though they were passwords?
So potentially you could have something set up like this.
Have a hidden input type that simulates the password values
So I guess jquery wise it would be
//everytime the password changes hidden changes with it.
$('#passwordId').change(function() {
$('#hiddenID').val() = $('#passwordId').val();
});
html:
<input type="password" id="passwordId" />
<input type="hidden" id="hiddenID" />
So this would allow you to validate the hidden input which would be the same value as the password.
First "hack" I can think of would be to add a "data-changed" attribute to the input="password" field, then attach an "onchange" event to the password field that sets "data-changed" == true, so that way you can validate if the value "password" was in fact entered by the user (data-changed == true) or if it is being submitted by the placeholder plugin itself.
While these answers were coming in, I had an epiphany of my own. At first glance, it appears to work. I'll check out the other answers and accept whichever approach looks like it will work best and be the least "hacky".
I came up with this approach when I discovered that the problem only exists when the field is empty (still has placeholder text), and as such, only will not pass "required" validation. My fix is to change it to type=password when content is entered.
My approach:
$('#password, #password_confirm').keyup(function(){
if ($(this).attr('type') === 'text') {
if ($(this).val().length > 0) {
$(this).attr('type', 'password');
}
} else if ($(this).val() == "") {
$(this).attr('type', 'text');
}
});

jQuery: password field with readable label?

I wrote this very simple function for my current project called insidelabel() that let's me add a description (label) for an input field inside of the input.
//Label inside of inputfields
function insidelabel(selector, name) {
$(selector).val(name);
$(selector).css({'color':'#999'});
$(selector).focus(function () {
//Input Value
if ($(this).val() == name) { $(this).val(''); }
$(this).css({'color':'#000'})
});
$(selector).blur(function () {
if ($(this).val() == '') { $(this).val(name); }
if ($(this).val() == name) {
$(this).css({'color':'#999'});
}
});
}
insidelabel('.t', 'name');
insidelabel('.p', 'enter password');
So when an input is focused the text disappears and when it blurs it has the same text again.
<form method="get" action="">
<input type="text" class="t" value="" /><br/>
<input type="password" class="p" value="" />
</form>
However now I wonder how I could extend that function to have a label inside of password fields as well! Sounds weird... Explanation: I want a password field (with type="password") to have a readable label (like "enter password") inside of it. Once the user enters text the password should be unreadable (dotted). Really bad explanation, I know, but I think you might get what I mean.
I wonder what's the best way to do that? Should I query if an input field is type="password" and if so I set it to type="text" - once text is entered I set it back to type="password" again. Any idea what's the best solution for that?
Here is my example: http://jsfiddle.net/R8Zxu/
If you use a real <label> positioned under the (transparent) <input> instead of faking it with the value attribute (which has some major accessibility implications) then you can do something like: http://dorward.me.uk/tmp/label-work/example.html
Don't try to change the type of an existing input. Internet Explorer won't let you.
OK for web applications, but if you want to use page on iPhone application then it does not works properly, for correct answer see refer this - http://blog.stannard.net.au/2011/01/07/creating-a-form-with-labels-inside-text-fields-using-jquery/
Yes, that would be the right approach. This is known as a 'watermark' on a text field, and since password input fields use a different text display mechanism, when the watermark is active, you would want to switch it to a text type. OnFocus, you would switch it out (and if needed) focus on the new text field.
Just remember, you'll want to do the conversion to a type="text" before messing with the value; there are restrictions when it is a type="password".

How can I dynamically change the style of some text depending on user input?

First, let me start off by saying that I know absolutely nothing about JavaScript or client-side scripting. All of the programming I've ever done has been server-side, mostly PHP, with some Java thrown in too for good measure.
So, I have absolutely no clue where to start with this problem. I have an application with very strict password rules. Users receive a default password when they first are given an account, and must change it immediately. However, no one ever reads the password requirements the first time, and as such, it always takes multiple tries to create a new password.
So, I've created a table like this:
<table>
<tr><td align="right">• Not be the same as your old password</td><td align="left">Not Met</td></tr>
<tr><td align="right">• Not be fewer than eight characters in length</td><td align="left">Not Met</td></tr>
<tr><td align="right">• Contain at least one number</td><td align="left">Not Met</td></tr>
<tr><td align="right">• Contain at least one uppercase letter</td><td align="left">Not Met</td></tr>
<tr><td align="right">• Contain at least one lowercase letter</td><td align="left">Not Met</td></tr>
</table>
//Later on, inside some <form> tags
<tr><td align="right">Old password: </td><td align="left"><input type="password" id="oldpass" name="oldpass" tabindex="1" /></td></tr>
<tr><td align="right">New password: </td><td align="left"><input type="password" id="newpass1" name="newpass1" tabindex="2" /></td></tr>
<tr><td align="right">New password, again: </td><td align="left"><input type="password" id="newpass2" name="newpass2" tabindex="3" /></td></tr>
What I want to have happen is while the user enters text in the fields, JavaScript (I guess) runs in the background and changes the "Not Met" text to "Met" and makes it green or something if the password validates. What is the best way to do this?
TIA.
Off the top of my head, you could create a function that contains all the validation rules you need, e.g:
function validatePass()
{
var error = false;
var oldPass = document.getElementById("oldPass").value;
var newPass = document.getElementById("newPass").value;
if(oldPass != newPass) {
error = true;
}
if(error) {
document.getElementById("someCellId").innerText = 'Not Met';
} else {
document.getElementById("someCellId").innerText = 'Met';
}
//set error to false for the next rule
error = false;
//more rules
//possibly using
//regular expressions
//and referencing appropriate
//not met and met table cells
}
Attach that to the keydown event of all three text boxes, e.g.:
<input type="password" id="oldpass" name="oldpass" tabindex="1" onkeydown="javascript:validatePass()" />
That should be a start.
Depending on what javascript framework you are using (if any), the implementation will be different. But the concept will be the same:
1 - You should observe the onchange event of the given text input where the password is being typed.
2 - When the event is triggered, it should call a function that would validate if the password meets the minimum requirement, so you would also need a function to make that validation.
3 - If it does have the minimum requirements just change the text and style of the specific span.
For Prototype JS it would be something like (imagining that the first table you shown had an id for the DOM parsing):
function isValid(elem){
// example:
if($(elem).value.length < 8) return false;
return true;
}
$('newpass1').observe('change', function(){
if(isValid('newwpass1'){
// it would be easier and faster with an id in the table cell
var elem = $$('table#tableid td')[8];
elem.innerHTML = 'Met';
elem.setStyle({color:'green'});
}
});
You could also use a ready to use solution like jQuery Validation and skip the in-house coding for all this validations.
This would depend on where the validation logic resides (as you mentioned this was a requirement). If you have a server side (asp.net/php/asp/coldfusion, etc) chunk of code (non ajax enabled then you would do this on the "post back" from the user. If you want to do this in java script then you would have to a) have the text validation performed via javascript or use javascript Ajax call to get the validation via the server side of things.
Then, you could use a library like jQuery + CSS to go ahead and change the colors, etc...
I believe in asp.net there are validation controls that will do this for you. Ajax as well.
First problem I see is:
Not be the same as your old password
are you sending the hash of the old password + salt and comparing it? If so you would also have to be sending your salt.
My suggestion is do this on the server side. The other requirements you could do in javascript, but you'd also want to have the same requirements on the server side. So for consistency you'd be better off keeping all of the validation in the server-side.
You can submit via ajax if you really don't want the to load another page, but doing all of the validation in javascript is probably not the best plan
enter code hereYou would need to use events. First you would need to attach an event to the textbox like so,
/* *this* passes a reference of the text box to the validateBox function */
<input type="password" id="oldpass" name="oldpass" tabindex="1" onkeydown="validateBox(this)"/>
I have used onkeydown so that validations happens when user in entering values in the textbox. (for other types of events refer link text)
Now you would need to write your business logic for the validateBox function. It is always a good practice to write this inside the inside section like so,
<head>
....
<script>
function validateBox(currentTextBox) {
/* this passed from the */
if(currentTextBox.id == "blah") {
// to perform validation according to the referenced textbox
if(currentTextBox.value == "blah") {
alert(" met ");
// in practice you would need to create a initially hidden div
//element & populate the content of the div accordingly. & then unhide it.
}
}
}
</script>
</head>
I would strongly suggest using javascript libraries/frameworks like jQuery etc. They make your life very easy & more productive!

Is there anyway to disable the client-side validation for dojo date text box?

In my example below I'm using a dijit.form.DateTextBox:
<input type="text" name="startDate" dojoType="dijit.form.DateTextBox" constraints="{datePattern:'MM/dd/yyyy'}" value='<c:out value="${sessionScope.adminMessageForm.startDate}"/>' />
So for example, if the user starts to enter "asdf" into the date the field turns yellow and a popup error message appears saying The value entered is not valid.. Even if I remove the constraints="{datePattern:'MM/dd/yyyy'}" it still validates.
Without going into details as to why, I would like to be able keep the dojoType and still prevent validation in particular circumstances.
Try overriding the validate method in your markup.
This will work (just tested):
<input type="text" name="startDate" dojoType="dijit.form.DateTextBox"
constraints="{datePattern:'MM/dd/yyyy'}"
value='<c:out value="${sessionScope.adminMessageForm.startDate}"/>'
validate='return true;'
/>
My only suggestion is to programmatically remove the dojoType on the server-side or client-side. It is not possible to keep the dojoType and not have it validate. Unless you create your own type that has you logic in it.
I had a similar problem, where the ValidationTextBox met all my needs but it was necessary to disable the validation routines until after the user had first pressed Submit.
My solution was to clone this into a ValidationConditionalTextBox with a couple new methods:
enableValidator:function() {
this.validatorOn = true;
},
disableValidator: function() {
this.validatorOn = false;
},
Then -- in the validator:function() I added a single check:
if (this.validatorOn)
{ ... }
Fairly straightforward, my default value for validatorOn is false (this appears right at the top of the javascript). When my form submits, simply call enableValidator(). You can view the full JavaScript here:
http://lilawnsprinklers.com/js/dijit/form/ValidationTextBox.js

Categories

Resources