chnselim chnselim - 2 months ago 17
Javascript Question

Regular Expression: Allow only characters a-z, A-Z

ExtJS 5.1

Let's say I have an example like that, I want user's name-surname so I don't want any numbers or special chars, I tried so many possibilities but couldn't make it:

var controller=this;
var refs = controller.getReferences();
var exp = '/^([^0-9]*)$/';

onButtonClick: function(button, e, eOpts) {
if(refs.nameSurname.value.match(exp)){
Ext.Msg.alert('ERROR', 'BlaBla');
}
}


With this code, I have no error when i enter a number to text field...

Thank you.

Answer

Assuming you need to actually match a string that has no digits...

You should not enclose the regex literal with single quotes, remove them. You do not need the capture group, you can remove ( and ).

Use

var exp = /^[^0-9]*$/;

Now, to check if a string matches a regex, you will be safer using a RegExp#test().

See the demo below:

var refs_nameSurname = "Som8ehere";
if(!(/^[^0-9]*$/.test(refs_nameSurname))){
        console.log('ERROR');
}

However, you can reverse the logic, and show an error once a digit is found inside a string (simpler!):

var refs_nameSurname = "Somehere12";
if(/[0-9]/.test(refs_nameSurname)){
        console.log('ERROR');
}