0

I have used a javascript validation function to validate it. I've used it to see whether the text entered to the html textbox is alphabetic(No numeric characters allowed). The function is called during onkeyup and onblur. The only problem is even when numeric values or special characters are typed in the validation doesn't work. If I leave the field blank then it works(Displays that the field is left blank). Here's my javascript code:

function isAlphabetic(x,y){
    var exp = /^[a-zA-Z]+$/; 
    var a = document.getElementById(y).value;
    if(a=="" || a== null){
            document.getElementById(x).innerHTML = "You cannot leave this feild empty"; 
                return;
    }
    else if(a!="" && a!= null){
        if(y.match(exp)){
            document.getElementById(x).innerHTML = "";
            return;
        }
        else{
            document.getElementById(x).innerHTML = "Only enter alphabetic characters allowed";
            return;
        }

    }
    else{
        return;
    }
1
  • What is the value of y? Commented Sep 27, 2015 at 8:53

2 Answers 2

2

If you use y as an id of element, I suppose you shouldn't check it with your regexp. Instead you should check a:

if(a.match(exp)) {
Sign up to request clarification or add additional context in comments.

Comments

1

You don't need JavaScript anymore for any of this. Use the pattern attribute on the input field and the browser won't let the user enter anything that doesn't match, and use required to prevent submitting the form with an empty value.

Also, do you really want only ASCII letters? (are spaces allowed? how about non-ASCII letters such as "é"?)

2 Comments

Does the pattern attribute compatible with old browsers? And yeah only ASCII values including spaces
No, it's modern HTML so it won't work in older browsers (caniuse.com/#feat=input-pattern). Unless you're working in an obsolete corporate environment, that's not a problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.