JavaScript to match random number and text input - javascript

I'm trying to make a really basic anti-spam function where the script generates a random number and then the user has to type it in a text field in order for the form to validate. My problem is grabbing the value of the generated number to match it against the input. Here is how I generate the random number:
window.onload=function randomNumberGenerator()
{
var x=document.getElementById("number");
var randomNumber=Math.floor((Math.random()*100)+1);
x.innerHTML=randomNumber;
}
I was trying to get the number at validation like this:
var x=document.forms["contactForm"]["realPerson"].value;
var correct=document.getElementById("number").value;
if (x != correct)
{
alert("Please write in the correct number");
return false;
}
But after a while i realized that innerHTML doesn't put anything in the DOM that can be read (as least that seems to be the deal). So how can I retrieve that number to compare it when the form is submitted? I have thought about using a cookie, but that seemed a bit intimidating...
Thank you!

If you can access the generated number from client side, I think you lose the purpose. Better generate the random number in the server side and validate it after form submission .

You are going to just use innerHTML a second time, perhaps with a parseInt
var correct=parseInt(document.getElementById("number").innerHTML);

Related

What is a good way to change fields in livecycle-documents without triggering validations?

I got a form with lots of fields and many scripts so I broke it down to my very fundamental problem with this example:
Before printing I check if everything is filled out with:
Seite1.execValidate();
The validate XML source of the field:
<validate nullTest="error" scriptTest="error"/>
When clicking on the top-button I want different things to happen.
For example:
field.rawValue = "";
or (if it's a decimal field)
//isPauschal was set earlier to either true or false
field.value.decimal.leadDigits = (isPauschal)?"4":"2";
But then this happens:
Field goes blue (=it is empty) when setting its value to "" - this I want only to happen when I'm validating with the print-button.
Now I found a workaround:
field.mandatory = "";
field.rawValue = "";
field.mandatory = "error";
But if I were to write this every time I changed something that would trigger this my code would look pretty bad and much more confusing.
Can someone help me?
What could I do to easily validate my fields before printing and still being able to change them around with js at runtime without them making strange colors. ;)
I don't want to validate them individually - I wish to keep something like the execValidate() command so it automatically checks all the fields in a subform.
Let me know if you need any more information!

Acrobat XI Pro: Allow User Input to Override Auto-Calculate Formula

I have this form, an official form (a character sheet for use at an Organized Play Event for a role-playing game, if it matters to anyone), that someone kindly turned into a fillable PDF form. I asked a question earlier about checkboxes and auto-calcualtions, and got that to work...but now I need to account for another variable (situational doubling of the Proficiency Bonus) in some of my calculations. Unfortunately, this variable is not represented anywhere on this form, and I can't just add fields to the form (it being an official form, at least when printed). Without adding more fields to the (printed) form, how can I account for this additional variable?
I thought about just allowing the user to override the auto-calculation by typing in the field, but I can't figure out how to make that happen. Is this a good solution? Is this relatively simple to code?
If your answer involves adding code to my form, please include a code snippet I can modify, and a description of where I should insert it into my existing code, or if there is somewhere else I need to be adding it instead.
Code Sample:
//check bonus = stat bonus + applicable proficiency bonus
var profUse = this.getField("SklAcrProf").value;
var stat = Number(this.getField("DEX1").value);
var profVal = Number(this.getField("Proficiency Bonus").value);
var check = Number('-2');
if (profUse != "Off"){
check = stat + profVal;
}
else{
check = stat;
}
event.value = check;
If the form only needs to remain the same, when printed, the simplest solution may be to go ahead and add the fields that you need. You can set them up, so that they are "visible but doesn't print". This option can be selected in the Form Field drop-down list, in the Text Field Properties, General Tab, under Common Properties.
This way, you can still incorporate the data in your formulas, but it has no affect on the printed document.

Validation function for multiple inputs

I have a form with 2 number inputs and I am trying to validate it using the jQuery Validation plugin. I want to allow the form to be submitted only if the sum of the values is less than or equal to 10. For example, I want to allow 3 and 6, but not 7 and 8. How can I do this?
I was able to come up with something that works but I think it is inelegant and fragile to arbitrarily apply the rule to one input and use an attribute on that input to refer to the other input. I looked in the documentation for the plugin and I don't see any way of defining a validator that is meant to be used on more than one input. Can anyone think of a simpler way?
As far as the jquery validation plugin. No. A simpler way. Yes write your own in plain javascript.
function mySubmitfuntcion()
{
var myvar1 = document.GetElementById("1").value;
var myvar2 = document.GetElementById("2").value;
if(myvar1 + myvar2 <= 10) {
return true;
}
else {
alert("Please enter valid values");
return false;
} // end if
} // end function
returning false stops the mySubmitfunction() from completing.
In my experience writing custom validation scripts works better because you have more control. Remember to add the validation function to a button or the forms onsubmit event.

Javascript validation to allow maximum of 3 commas

I want a Javascript validation that allows maximum of 3 commas in a text field user to enter a number or text in format
123,456,789,0000
meaning 3 Commas(,) are allowed, there could be any number of digits/letters between commas. User may choose to enter only 2 Commas i.e. 3 values but max number of Commas that would be allowed are 3
for eg
a,bb,ddddd,eeeee (4 tags)
a,cc,bbbbb (3 tags)
What I am trying to achieve is user is allowed to enter only 4 comma separated tags thus making sure user cannot flood the article with 100's of tags
var txt = '123,456,789,0000';
if( /^([^,]*,){0,3}[^,]*$/.test( txt ) ){
// good
}else{
// bad
}
change the * to a + if you want to ensure that there aren't two commas in a row, e.g.: 12,,345
If you have control on server side, I suggest doing the validation there.
Because If you try to do the validation on the client using java script, it can be circumvented by either turning off java Script all together, or using Firefox's FireBug extension by manipulating or manually executing a request, bypassing your java script validation altogether.
But if you really still want to do some kind of validation in javascript, you can do something like the following:
Given this input field <input id="txtInput" type="text" />
You could bind a keyup event (pay attention to people attempting to paste from the clipboard, keyup will not catch it if they do it via context menu)
$('#txtInput').keyup(function(){
//This splits up the string value of the text box into an array
//wherever a coma appears
var tags = $(this).val().split(',');
//These would be your tags, without the coma, count them to find out how many
//the user tried to enter.
if (tags.length > 4)
alert('there is more than 4 tags');
});
Of course this is only an example, but you could adapt the idea to your needs. You don't have to bind this to the keyup event, you could bind this to a click event on the submit button or something, it all depends on your needs.

Limit an html form input to a certain float range

Is there a way to limit a form input field to be between certain number range, say (0,100)
I'm filtering the input in the onkeydown event, to accept only numbers, the problem
is I want to reject a number if that number would make the input to go out of range
So I need a way to see if the current value of the input plus the key the user is pressing
will sum up between the range.
I tried using:
if((parseFloat(this.value) + parseFloat(String.fromCharCode(e.keyCode)) > 100){
return false;
}
the thing is e.keyCode can return different codes for the same number, right now is returning 57 for the
number 9, but 105 if i press the number on the numpad.
Is there a way to accomplish this?
Personally, I would just check it when the field loses focus (or when the form is submitted). Popping up errors as the user is typing (or preventing their keystrokes from registering in the field) is usually just going to annoy them.
And of course you probably knew this already, but make sure you check the value on the server side after the form is submitted as well. Never rely on javascript validation!
Trying to anticipate what the resulting value is going to be is harder than you think. Remember the user might be pressing backspace, or the cursor might not be at the end of the field, or the user might have part of the value selected, to be replaced on next keypress, and so on. It's also possible to manipulate the text field through mouse operations you won't get any say in.
The traditional approach is to put your validation on the ‘keyup’ event instead of ‘keypress’. Then you get the full, post-change value of the field. You don't get the chance to deny the keypress, but you can reset the field to the last-known-good value instead.
But either way it's best not to try to constrain input too tightly, because this can make it terribly difficult to type. For example, “12.” is an invalid number you might want to deny... but if you did, it would become very difficult to type “12.3”! Better to allow any input, but signal when the current input is out of bounds, by some mechanism (eg. turning the text red is common).
Adding the current value plus the float value of the character typed is not what you want. Think about if the current value is 99.0 and the user types a "5", the actual value is 99.05 but your expression would evaluate to 104.0. You need to append the key character to the current value before parsing anything into a float.
As for the key code, here is a reference to the javascript key codes. Using that you could write your own function like this:
function fromKeyCode(code) {
var asciiCode = code;
if (code > 95 && code < 106) {
asciiCode -= 48;
}
return String.fromCharCode(asciiCode);
}
var total = new Number(20.00);
alert(total.toFixed(2));
That will allow you to set a fixed width on the precision of 2 decimal places. In this case I am making sure with a js required field check that money only has 2 spots after the 2.
I'm not sure if I understand your question fully, but check the Number() methods, there has to be something there to help you.
You can catch the input on keyup, after the value contains the new input.
Then just look at the value-
inputelement.onkeyup= function(e){
e= window.event? event.srcElement: e.target;
var val= parseFloat(e.value) || 0;
e.value= Math.max(0, Math.min(100, val));
}

Categories