开发者

need to return true or false based on if value in text field is a specific number

开发者 https://www.devze.com 2023-01-10 21:05 出处:网络
I am looking to return true if the user entered 4 into the input field. function validateAddition() { if($(\"#validateAddition\").val() == 4) {

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,o开发者_开发问答nlyNumber,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.


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.


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."
},


0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号