javascriptsencha-touchsencha-architectsencha-touch-2.1

How to do alphanumeric validation in sencha touch for textfield


How do I implement alphanumeric validation in Sencha Touch for textfield? I have tried this way:

regex: /^[a-zA-Z0-9]*$/,
regexText: 'Invalid value in field',

But it is not showing any error when I type the # symbol or any other special character.


Solution

  • As pointed out by @Benoit Cuvelier in the comments:

    According to docs: docs.sencha.com/touch/2.1.0/#!/api/Ext.field.Text Textfield component has no "Regex" properties (but in ExtJs it has). I think you should check the value on the change event

    That said, a simple implementation using the keyup listener could be:

    {
        xtype: 'textfield',
        label: 'Only alphanumeric values',
        name: 'alphanumeric',
        regex: /^[a-zA-Z0-9]*$/,
        listeners: {
            keyup: function(field) {
                var value = field.getValue();
                if (value.length && !value.match(field.config.regex)) {
                    field.setStyle('border: 1px solid red;');
                } else {
                    field.setStyle('border: 0;');
                }
            }
        }
    }
    

    https://fiddle.sencha.com/#fiddle/ttl