Sophia111 Sophia111 - 4 months ago 12
HTML Question

Check if input is only alphabets in javascript using IF ELSE statement

I have an input field for which I need to make sure the input is only and only characters from the alphabet, with no:


  • numbers

  • special characters

  • number + alphabet combinations



I want to do this using if else statement only. So far the code is:

HTML:

<form id="myform" onsubmit="return check();" >
<input class="input" type="text" name="firstname">





And JavaScript is:

function check() {
var x = document.forms["myform"]["firstname"].value;
if (x == null || x == ""){
myform.action="firstnameerror.html";}
if (isNaN(x)) {
myform.action="lastname.html";
} else {
myform.action="firstnameerror1.html"
}
}

Answer

You can check it using regular expressions (RegExp), specifically with the .test() function:

if(/[^a-zA-Z]/.test(x))
    // code to throw error

This will run the code to throw an error if any non-alphabetic character is contained in x.

Comments