最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - TextField Valdiation in Appcelerator Titanium - Stack Overflow

programmeradmin3浏览0评论

How can i Valdiate my TextField in Titanium or in JavaScript to restrict it to numbers only.

var txt_appt2 = Titanium.UI.createTextField({
    top:2,
    left:240,
    width:75,
    color:'#000',
    backgroundColor:'#fff',
    font: {fontSize: 12}
});

How can i Valdiate my TextField in Titanium or in JavaScript to restrict it to numbers only.

var txt_appt2 = Titanium.UI.createTextField({
    top:2,
    left:240,
    width:75,
    color:'#000',
    backgroundColor:'#fff',
    font: {fontSize: 12}
});
Share Improve this question asked Apr 7, 2011 at 7:36 theJavatheJava 15k48 gold badges134 silver badges174 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 9
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./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. That's the proper event since it fires every time the value is changed. I.e. 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.

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.

// XML

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

// Alloy.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;
    }
};
发布评论

评论列表(0)

  1. 暂无评论