How can i Valdiate my TextFie开发者_StackOverflow社区ld 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}
});
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/
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;
}
};
精彩评论