简体   繁体   English

Titanium Appcelerator-在文本字段中输入出生日期

[英]Titanium Appcelerator - Entering Date of birth in textfield

I am trying to format my textfield where user will enter his date of birth. 我正在尝试设置用户输入其出生日期的文本字段的格式。

Currently when user starts typing the 3rd character, i am adding "/". 当前,当用户开始输入第三个字符时,我正在添加“ /”。

But i need to add "/" when user types the 2nd character. 但是当用户键入第二个字符时,我需要添加“ /”。

Please find my code below, 请在下面找到我的代码,

$.dobTextfield.addEventListener("change", function (event) {
    var dobValue = $.dobTextfield.value;

    dobValue = dobValue.replace(/\//g, '');
    var newVal = '';
    var sizes = [2, 2, 4];

    for (var i in sizes) {
        if (dobValue.length > sizes[i]) {
            newVal += dobValue.substr(0, sizes[i]) + '/';
            dobValue = dobValue.substr(sizes[i]);                   
        }
        else
            break;
    }           
    newVal += dobValue;
    $.dobTextfield.value = newVal;  
});

Recommendation: Use a Date Picker 建议:使用日期选择器

I would recommend that you replace your textfield with a label (possibly styled to look like a textfield if that is important). 我建议您用标签替换文本字段(如果重要的话,样式可能看起来像文本字段)。

I would then add a click event to the label which would display a date picker. 然后,我将click事件添加到将显示日期选择器的标签中。 Date Picker Docs 日期选择器文档

You could the update the label's value based on date picker's value. 您可以根据日期选择器的值更新标签的值。

Solution to your existing code 现有代码的解决方案

var oldValue;

$.dobTextfield.addEventListener("change", function (event) {
    var dobValue = $.dobTextfield.value;

    // this checks to see if the user has removed a slash bu hitting backspace
    // without this the user would not be able to delete a back space
    if (oldValue == dobValue + "/") {
        return;
    }

    var newVal = '';
    var sizes = [2, 2, 4];

    if (dobValue.length == 2 || dobValue.length == 5) {
        dobValue += "/";
    }

    $.dobTextfield.value = dobValue;  
    oldValue = $.dobTextfield.value;
});

This will enter the slash when the user types the 2nd character and will also allow the user to delete a slash using the backspace if they need to edit the date. 当用户键入第二个字符时,这将输入斜杠,并且如果需要编辑日期,则还允许用户使用退格键删除斜杠。

Other considerations 其他注意事项

Your current textfield allows the user to enter an invalid date. 您当前的文本字段允许用户输入无效的日期。 For example the user could enter a date such as 60/99/2018. 例如,用户可以输入日期,例如60/99/2018。 Using a date picker would remove the need for such validation. 使用日期选择器将消除对这种验证的需要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM