javascript validation - ignore default field value - javascript

trying to ignore the default value (used a field hint for accessibility) of a field when the form is going
through it's validation.
The validation is in javascript:
if (giftCardNumber >= 'xxxxxxxxxxxxxxx' && giftCardNumber <= 'xxxxxxxxxxxxxxxxx' ) {
giftAlert (incdpy_msg_065,"frmGCD_"+formIndex+"_Number");
if ((typeof TeaLeaf != "undefined") && (typeof TeaLeaf.Client != "undefined") && (typeof TeaLeaf.Client.tlAddEvent != "undefined") ) { // Tealeaf Include
var nVO = { ErrorMessage :incdpy_msg_065}
var subtype="CustomErrorMsg";
TeaLeaf.Event.tlAddCustomEvent(subtype, nVO);
}
return false;
}
I assume it's a fairly simple line - if(giftCardnumber === "Enter gift card")...
xxx's are for security reasons.
Or can I just clear all default values on focus and on submit?

You can just check against the defaultValue property:
if (element.value == element.defaultValue) {
// it has its default value
} else {
// it has some value other than its default
}
The usual way is to use onfocus and if value == defaultValue, set the value to '' (empty string). Then onblur, do the opposite (i.e. if value == '', set to defaultValue).

Yes - if you know what the default value is, and can validate against it, this is the most straightforward way of doing it.

You basically need to test for that value yes. Then it depends if you want to prevent the form from being submitted or send an empty value to the server.
Did you try that and encounter a problem ?
edit:
As you say clearing the values on focus would be nice (for the user) but not sufficient since the user can still submit the form without 'touching' the field. In the submit you can just do
if(giftCardNumber === "default value") {
giftCardNumberField.value = "";
}
Provided you have access to the field this will simply send an empty value to the server. This will also have the annoying habit of leaving the field blank (ugly if the page does not get submitted because the form was invalid or because you do it through ajax).
Actually I don't know what's the best practice for this. Looking at the ext docs I see that their Textfield will just submit its empty text if given an html name.

Related

Boolean and text field validation - Javascript

I have a form that posts to itself with a text field (for SMS number) and a boolean field (for SMS opt in). I can't seem to get the syntax correct for validation when the end-user goes to post the form.
If they select the bool for opt in, then the form should check the text field for the sms number and if the sms number is empty, display an error.
Here's my javascript snippet:
if (document.getElementById("smsOpt").checked = 'true' && document.getElementById("smsNum").value = ''){
error += "smsOpt";
document.getElementById("smsOpt").focus();
document.getElementById("smsOptError").style.display='block';
}
You can do something like this:
if (document.getElementById("smsOpt").checked && document.getElementById("smsNum").value.trim() == ''){
error += "smsOpt";
document.getElementById("smsOpt").focus();
document.getElementById("smsOptError").style.display='block';
}
For checkbox, the checked property is of type boolean so use of only "checked" is fine. And for the second property you can compare it with an empty string. Single = operator in JS is for assignment and not comparison.
You have to use == or === instead of = in vary conditions.
if (document.getElementById("smsOpt").checked == 'true' && document.getElementById("smsNum").value == ''){
error += "smsOpt";
document.getElementById("smsOpt").focus();
document.getElementById("smsOptError").style.display='block';
}
There is actually no need for using any equality operators in this case. You can do something like this:
if (document.getElementById("smsOpt").checked && !document.getElementById("smsNum").value){
error += "smsOpt";
document.getElementById("smsOpt").focus();
document.getElementById("smsOptError").style.display='block';
}
But if you want to use them, then do it with triple === or double equality == operators. You can check the differences between theese two here.
In JavaScript = is only for assignment, so your if-statement is setting checked=true on the input rather than checking what is it. (Or it actually sets it to true no matter what it was and then evaluates the result of setting the value which will always be true)
You need to use == or better ===
if (document.getElementById("smsOpt").checked === true && document.getElementById("smsNum").value.trim() === '') {
I added trim() also so it ignores if you just insert spaces.

jQuery - Simple validation for two inputs

I have two inputs: the first one is X - file upload. the second one is Y- an input for an URL.
So far I have a code that checks if Y is valid then remove the attribute required for X. otherwise I want the X to be required.
$(Y).blur(function(){
if ($(this).is(':valid') == true) {
$(X).removeAttr('required')
} else if ($(this).is(':valid') == false) {
$(X).attr('required');
}
});
for some reason this code works when the input Y is valid it removes the attribute. But let's say the user regrets and wants to leave Y blank, it doesn't return the required attribute for X.
Tried to keep the explanation as simple and clear as possible. If there is a misunderstanding I'll try to edit this question and make it clearer.
The easiest way is:
$(Y).blur(function(){
if ($(this).is(':valid') == true && $(this).val() != '') {
$(X).removeAttr('required')
} else if ($(this).is(':valid') == false || $(this).val() == '') {
$(X).attr('required');
}
});
In that case when user removes the content, required attribute will be returned back (dont forget to add trim function, I didnt use it in the sample).
I would recommend to capsulate this logic into validation functions. I also dont like blur event (usability is bad), I would recommend onchange event for field validation.

How To Check For Empty Fields In HTML Form With JavaScript

I'm checking a website registration form with JavaScript code and onchange listeners.
Empty fields/spaces need to be checked for first before checking for illegal characters, too long strings, etc.
I've read this.
But for a null string,
if (field.value ==="")
alert("Empty field!");
this will not generate the desired alert.
People at the end of the above thread suggested that recent browser versions might not accept such a statement.
So, how do I sort out empty/blank/ignored fields ?
EDIT 1
I've already tried
if (!field.value)
but it only provides an alert if the user has already typed some characters in the field and immediately deleted them before entering a blank field. It will not provide an alert just by clicking the mouse on it and then tabbing on to the next field. It looks like I may need to assign a null value to these form fields at the outset . . I am using implicit adding of the changeEvent listener, i.e. on seeing a value explicitly assigned to the onchange attribute of an element, it is activated without any addEventListener(..) statement.
Also,
if (field.value.length == 0)
does not seem to produce any alert.
EDIT 2
Sorted, I think.
I was using the JavaScript null field check as part of a field-by-field validation check on a web form.
I was using onchange as the event handler. This was wrong. What was needed here was onblur since in the case of a completely null field (i.e. a field on which nothing had been entered before tabbing away from it), no change has been effected -- and therefore no onchange event occurs that would trigger a JavaScript alert.
Thanks for your efforts.
I was stuck on this one across a couple of weeks and only sorted it with the help of some experimental programming by a more experienced guy at work here.
In this script you can see an alert of your variable value ( a console.log would be lees noisy :)
The use of === is for type check but in your example does not make sense as you are using an empty string
<script>
var field= {};
checkEquality(field);
field.value = "";
checkEquality(field);
function checkEquality(object){
alert(object.value);
if (object.value === "")
{
alert("===");
}
if(object.value == ""){
alert("==");
}
}
You can use bellow code for check all four(4) condition for validation like not null, not blank, not undefined and not zero only use this code (!(!(variable))) in javascript and jquery.
function myFunction() {
var data; //The Values can be like as null, blank, undefined, zero you can test
if(!(!(data)))
{
alert("data "+data);
}
else
{
alert("data is "+data);
}
}

Why does this jQuery input value checker not work?

I need to check all the inputs to see if they are filled, in which case the submit button would become pressable and the user can submit their data safely:
unfilled = false;
$('.add-field').keypress(function(){
$('.add-field').each(function(){
if($(this).val() === ''){
unfilled = true;
} else {
unfilled = false;
}
})
console.log(unfilled);
});
This code works, but it has a strange twist; as the last empty input gains a character, it still returns true. If an input gains another character, only then it will return false. I am confused by this, as I understand that the .each() function is fired after a character has been added and the value of the input has been updated. Consequently, I do not see why it does not register that value.
You should set unfilled to false before entering the loop (but INSIDE the keyup).
In the loop you should only set unfilled to true when a field is emty and not set it to false again, otherwise you'll only know if the last field is filled in.
You could use filter and use keyup event instead for del keys:
DEMO
$('.add-field').keyup(function () {
var unfilled = !! $('.add-field').filter(function () {
return $.trim(this.value) === ""
}).length;
console.log(unfilled);
});
Here === means it is matching exactly the data types:
if($(this).val() === ''){
Replace it with == :
if($(this).val() == ''){
As far as I know, this is an 'issue' when using the KeyPress-event, because the Browser's UI Thread did not update the input field's value yet. Therefore the value currently is still 'empty' and thus true is returned; you can either use the KeyUp-event or try something like this: JavaScript keypress event get end value of textarea

Forcing statement after && to execute when statement before the && is false

I have set up form validation using a validate function that runs for a single field, changing its formatting and returning a Boolean. Then to validate the form I have
var isValid = validate(field1) && validate(field2) ... ;
I would like each invalid field to be highlighted but using this approach the validation stops as soon as an invalid field is reached (due to the way && works).
Obviously I could evaluate validate for each field as a separate statement and then combine the results afterwards, but is there some way I can force the &&'s to not stop after a false result, or some other way of keeping the code to one concise line?
You can break it out more logically (and readable);
var isValid = validate(field1);
isValid = validate(field2) && isValid;
isValid = validate(fieldN) && isValid;
You could use & as HMC suggested using !! to get a bool !!(a & b & c)
Or even var isValid = true == validate(field1) == validate(field2) == validate(fieldN);

Categories

Resources