输入字段根据输入的数据类型对数据进行不同的格式化

Input field formats data differently-depending on the type of data inputted

本文关键字:输入 格式化 字段 数据类型 数据      更新时间:2023-09-26

我有一个输入字段,它链接到一个数据库,该数据库可以采用邮政编码或城市。问题是邮政编码需要采用某种格式,即

CB30AX
cb30ax
sg120js
SG120JS

大写并不是一个真正的问题,但不能包含任何空格。。。经过研究,我成功地把这个脚本放在了下面:

<script>
//make sure postcode goes in correct format
$(document).ready(function ()
    {
        $('input[name="sCity"]').change(function (){
            var postCode = $(this).val();
            $(this).val(postCode.replace(/'s/g, '').toUpperCase())
        })
    });
</script>

它将所有字母大写,并完美地删除空格,然而,在英国,有些城市,如:Leigh On SeaCanvey Island,都有空格,所以上面的代码将其变成一个单词。我如何让代码检测输入是城市还是邮政编码(可能验证邮政编码,如果返回true,则相应地格式化?提前感谢!

这是一个FIDDLE

如果有数字,那么假设它是邮政编码,否则它是城市名称。

http://jsfiddle.net/0zdd6cr3/2

$('input[name="sCity"]').change(function () {
    var postCode = this.value.toUpperCase();
    if(/'d/.test(postCode)) postCode = postCode.replace(/'s/g, '');
    $(this).val(postCode);
});