-2

I am new to JavaScript. I have created a form which submits details to a database. I have different textboxes, some need to accept Only Letters and some to allow only numbers.

I got this code while doing some research, but this code tells me of an invalid pattern. Can you help me so that this code will allows Only Letters. I tried to modify the code so that it takes only letters but I failed.

function f_check_Lett(form){    //Only letters and numbers allowed  

    var text = form.bucketname.value;
    alert(text);

    var filter = /^[A-Za-z0-9]+$/;
    if (filter.test(text)) {
        form.submit(); 
    } else {
        form.bucketname.select();
        alert("Only Allow letters and numbers!");
    }
}  

IT Forward
  • 367
  • 2
  • 7
  • 28
  • 4
    Get a good JavaScript book or find a good tutorial. You have to be able to solve simple tasks if you want to do anything with JavaScript, and you should be able to write this from scratch in at most ten minutes. – tckmn Jul 31 '13 at 06:14
  • you have 0-9 in regular expression, it will allow numbers also. – Tahir Yasin Jul 31 '13 at 06:14
  • 1
    Please tell me you are also doing validation on the server end and not just whacking the text entry straight into the database? – slugster Jul 31 '13 at 06:15

3 Answers3

3

use the filter as

var filter = /^[A-Za-z]+$/;

in your filter [A-Za-z0-9] will accept any character of: 'A' to 'Z', 'a' to 'z', '0' to '9'

since you only need letters, remove the 0-9 from the filter.

Damith
  • 62,401
  • 13
  • 102
  • 153
  • Hi Damith, when i try to insert only letters, it highlighted the text box and says "Please match the requested format" – IT Forward Jul 31 '13 at 07:43
0

Try this:

var filter = /^[a-zA-Z]+$/.test('sfjd')

You should definitely give jQuery Validate Plugin a try though. I've used it in many of my projects and it's very easy to implement.

Good luck!

karlingen
  • 13,800
  • 5
  • 43
  • 74
  • Even if this is correct it is a poor answer. Take some time to explain it! I'll rescind my down vote once you have. And please don't just submit a quick and dirty answer then use the 5 minute grace period to shape into what it should have been, you'll simply be contributing to the FGITW problem. – slugster Jul 31 '13 at 06:16
  • @slugster How is this a poor answer? – karlingen Jul 31 '13 at 06:17
  • 2
    Because you originally had one line of code and the text "Good luck!". That is a bad answer. – slugster Jul 31 '13 at 06:18
0
// Only letters and numbers allowed
function f_check_Lett(form) {

    var text = form.bucketname.value;
    var check_format = isNaN(text);
    if (check_format == "false") {
        // your code go here 
    } else {
        // your code go here
    }
}
Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
Mohan
  • 1
  • 1