无法弄清楚如何使用jQuery表单和.length

时间:2021-06-15 21:19:46

I am currently working on a project which involves authenticating form fields based on the length of the strings in the fields. For example, the zip field needs to be atleast 5 characters. This is the code I have so far;

我目前正在开发一个项目,该项目涉及根据字段中字符串的长度验证表单字段。例如,zip字段需要至少5个字符。这是我到目前为止的代码;

$(document).ready(function() {
//Building the Address from the Form
var address = document.getElementById("address");
var city = document.getElementById("city");
var state = document.getElementById("state");
var zip = document.getElementById("zip");

var addressobject = buildAddress(address.value, city.value, state.value, zip.value);

function buildAddress(address, city, state, zip){
    addressobject = {
        address: address,
        city: city,
        state: state,
        zip: zip,
        toString: function(){
            return (this.address + "," + this.city + "," + this.state + "," + this.zip);
        }
    }
    return(addressobject);
}
//Validation Function
$("#btn").on("click", function(addressobject) {
  if(address.zip < 5){
    alert("good");
  } else
    alert("bad");
});

});

There are other parts to this project however right now I just need to get this authentication part working. Again, I can't seem to get the (address.zip < 5) working, instead as of right now any input in the zip field produces an alert box of "bad". The above document.getElementById is referencing the div input id from the html page. Should I be referencing something else instead maybe?

这个项目还有其他部分,但是现在我只需要让这个认证部分正常工作。再一次,我似乎无法使(address.zip <5)工作,而现在,zip字段中的任何输入都会产生一个“坏”的警告框。上面的document.getElementById引用了html页面中的div输入id。我应该引用其他东西而不是吗?

1 个解决方案

#1


0  

Note that any text input is a string and cannot be evaluated as a number. You either need to convert it to a number via parseInt (or parseFloat) and compare it against a five digit number that is the minimum NUMBER that you want to validate or get the length of the inputted string from the text input and compare that against the 5 characters you require using the .length property.

请注意,任何文本输入都是字符串,不能作为数字进行求值。您需要通过parseInt(或parseFloat)将其转换为数字,并将其与要验证的最小NUMBER的五位数进行比较,或者从文本输入中获取输入字符串的长度,并将其与使用.length属性需要5个字符。

#1


0  

Note that any text input is a string and cannot be evaluated as a number. You either need to convert it to a number via parseInt (or parseFloat) and compare it against a five digit number that is the minimum NUMBER that you want to validate or get the length of the inputted string from the text input and compare that against the 5 characters you require using the .length property.

请注意,任何文本输入都是字符串,不能作为数字进行求值。您需要通过parseInt(或parseFloat)将其转换为数字,并将其与要验证的最小NUMBER的五位数进行比较,或者从文本输入中获取输入字符串的长度,并将其与使用.length属性需要5个字符。