简体   繁体   English

Appcelerator Titanium 中的 TextField Valdiation

[英]TextField Valdiation in Appcelerator Titanium

How can i Valdiate my TextField in Titanium or in JavaScript to restrict it to numbers only.我如何在 Titanium 或 JavaScript 中验证我的 TextField 以将其限制为仅数字。

var txt_appt2 = Titanium.UI.createTextField({
    top:2,
    left:240,
    width:75,
    color:'#000',
    backgroundColor:'#fff',
    font: {fontSize: 12}
});
txt_appt2.addEventListener('change',function(e){
    txt_appt2.value = txt_appt2.value.replace(/[^0-9]+/,"");
});

Add添加

keyboardType:Titanium.UI.KEYBOARD_NUMBER_PAD,

to the TextField.到文本字段。

See example at http://www.lonhosford.com/lonblog/2011/04/06/titanium-limit-the-characters-in-a-textfield/请参阅http://www.lonhosford.com/lonblog/2011/04/06/titanium-limit-the-characters-in-a-textfield/中的示例

For those wondering why they are experiencing continuous loops and errors;对于那些想知道为什么他们会遇到连续循环和错误的人;

The problem isn't listening to the onChange event.问题不在于监听 onChange 事件。 That's the proper event since it fires every time the value is changed.这是正确的事件,因为每次更改值时都会触发它。 Ie Copy and paste, keypress and so on.即复制和粘贴、按键等。

On iOS users can copy and paste in characters even though you're only limiting to decimal / numeric keyboard.在 iOS 上,用户可以复制和粘贴字符,即使您只限于十进制/数字键盘。

Avoid trying to set the field value directly by referencing the text field property itself.避免尝试通过引用文本字段属性本身来直接设置字段值。 Instead, use the text field property returned when the text field is changed.相反,使用文本字段更改时返回的文本字段属性。 Doing it this way won't cause the onChange event to keep firing causing a never-ending loop.这样做不会导致 onChange 事件继续触发,从而导致永无止境的循环。

// XML // XML

<TextField keyboardType="Ti.UI.KEYBOARD_TYPE_DECIMAL_PAD" value="0.00" onChange="Alloy.Globals.helper.decimalFormat" />

// Alloy.js // 合金.js

Alloy.Globals.helper = {
    decimalFormat: function(e) {
        // Strip all characters from the input except digits
        var input = e.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');
        e.source.value = input;
    }
};

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

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