Question

I am looking to return true if the user entered 4 into the input field.

function validateAddition() {
  if($("#validateAddition").val() == 4) {
    return true;
  } else {
    return false;
  }
}

<input value="" 
class="validate[required,onlyNumber,length[0,1]funcCall[validateAddition]] text-input" 
type="text" id="validateAddition" name="validateAddition" />

Added this into the english language js file:

"validateAddition":{
    "nname":"validateAddition",
    "alertText":"* Your math is off, try again."}

This should be fine, let me know what you think is wrong.

Was it helpful?

Solution

http://www.w3schools.com/jsref/jsref_parseInt.asp

return (parseInt($('#validateAddition').val()) == 4)

EDIT: MooGoo is correct, I was mistaken as far as my explanation.

However is idea of using +val is probably not the best. While the method above WILL work as you require a much better solution would be as follows:

if(($('#validateAddition').val()-0) == 4)

The reason we want to -0 as opposed to +0 is simply because if it is a string and you want to perform any additional operations incase it is, you will no longer have the original string.

OTHER TIPS

If you want to allow other characters as well and return true only if the text of input field contains 4, you should do like this instead:

if($("#validateAddition").val().indexOf('4') != -1) {

It would make sence to compare the value to a string, since the value is a string. That allows you to use strict equals avoiding unnecessary automatic conversions. Also you can simplify the function.

function validateAddition() {
  return $("#validateAddition").val() === "4";
}

You can put your validation in the language file, looking something like this


"validateAddition": {
    "regex": /[0-3]|[5-9]/,//something that matches on all numbers but four
    "alertText": "* Your math is off, try again."
},


Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top