Validation function for multiple inputs - javascript

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.

Related

How to monitor input in javascript

I'm developing an extension for chrome that should check input fields in a form using REGEX
To do this, I need to get an input field, I do it as follows:
let input = document.getElementById("id_input");
After that, I have to add some function that whenever there is any change in the input, it applies a Regex in the value, formatting it in real time if the user enters some invalid value.
I tried to make a sketch of this code as follows:
input.addEventListener("change", function () {
let v = document.getElementById('search').value;
v.replace(/world/g, "universe");
});
For some reason it's not working, I don't have as much knowledge in javascript and I don't know if the code I made is wrong or if I need to add something else to it.

Mask Text Input to Validate MM/YY jquery-mask-plugin

Using jquery-mask-plugin I want to mask an input to only accept reasonable MM/YY
$('#expDate').mask("99/99"); works but it allows for 55/66 which is not an acceptable month.
How can I make it so the first part of the mask is <= 12
You cannot do this with just the jquery-mask plugin. As you noted, it only masks out certain TYPES of inputs, such as numbers (in general), letters, symbols, etc. It does not perform data validation (which is what you're asking for.
You can write a simple jQuery function that runs onblur, etc that rejects invalid combinations:
$('#expDate').blur(function() {
let val = $(this).val();
if (val.indexOf('/') > 0)
{
let first = val.split('/')[0];
if (first > 12) $(this).val('');
}
});
Alternatively, you can use the great jQuery Validate plugin:
https://jqueryvalidation.org/
To be clear, you want data validation beyond just basic input masking.

JavaScript to match random number and text input

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

How can I validate a form field value against a variable with jQuery Validate?

I'm sure there must be a simple solution to this..
I simply want to create a rudimentary human verification tool for an online form. In pseudo-code, something like
$answer = "foo";
if (form['question'] == $foo){
// Proceed
} else {
// Fail
}
The jQuery docs seem to have an equalTo method but this is to compare a form field with another form value..
Any tips greatly appreciated! :)
You need to have a look at JQuery Validation plugin at http://docs.jquery.com/Plugins/validation. Consider the following example:
You may change the rules as explained in the plugin to implement your custom validations.
Have you looked at this plugin? You can use it to make fields required, validate for certain value types (number, string, credit card, etc), and I believe you can write callback functions to validate for specific values.
http://docs.jquery.com/Plugins/validation
var answer = 'foo';
if ($('#question').val() == answer) {
// Proceed
} else {
// Fail.
}

Javascript events

I am completely confused here. So I am looking for a solution for the following problem:
I want to trigger some function(for now an alert box) using jQuery on an input field. Conditions are:
Input field always maintains the focus.
Input is fed from a USB device, which acts just like a keyboard input. So for 10 characters, there will be 10 keydown and keyup events.
Once input is filled with 10 characters, respective alert box should pop out.
Now the problem I am facing, how do I find out that input fed in is not equal to 10 characters, so throw an error alert box.(lets say just 5 chars came in input, how do I figure out the final count is 5, because there will be 5 keyup events)
You could show a message underneath/beside the input box instead of popping an alert box.
E.g. on every keyup event, check the string length, and if it's not 10, show that message.
If you really, really have to resort to alert box, you could do a timeout check, e.g. only perform the validation after 1000ms of key event inactivity. This could get very annoying on the user though.
You really have two problems here. One is just understanding the jQuery syntax (see the second part to my answer), and the other is - what is the best way to understand WHEN to throw up an error box.
To answer the second question first, my recommendation would be to not use an alert box to warn the user as they tend to be modal and really interrupt the flow of input. Secondly, as you said - how do you know when the person has stopped "typing." Unless you use some sort of timing mechanism (which is more trouble than it's worth), you don't. My suggestion would be to utilize a "div" within your HTML that shows there is an error UNTIL you reach 10 characters. Once that happens, you can hide the div. (And, of course, the div can be styled to look pretty in the meantime.)
So...how to do this...
Let's assuming your input field has an id of "myField." If you are using jQuery (which is in your tags), you would do something like this.
$(function() {
var keypresses = 0;
$('#myField').keyUp(function () {
keypresses++;
if(keypresses == 10) {
$('#error').hide(); // This is your div error with some error text in it.
// Do other stuff.
} else {
// Display an error.
}
});
Alternatively, if you don't want to use the keypresses variable, you can also use..
if($(this).val().length == 10) { }
The real issue is the fact that you are measuring in key press events, because not all key presses (even when the field has focus) will insert a character into field (for example returnesc). Therefore, you will need to measure the string length in order to validate the code before you start executing functions.
In actuality you don't even need jQuery to accomplish what you need, just bind the function call to a key press event, and only execute the function call if yourstring.length = 10
yourInput.onKeyPress(yourString.length = 10 && yourFunction());
Try -
$('#idofinputfield').keyUp(function () {
var length = $('#idofinputfield').val().length;
if(length <= 10){
alert("less than 10");
}else{
alert("greaterthan 10");
}
});

Categories