Ameer
Ameer

Reputation: 15

javascript form validation - letters only

I have written a code that only allows letters to be typed into a text field, but it is not working. Can you help me spot the errors, and find a solution please.

function allLetter(inputtxt) {
  var letters = /^[A-Za-z]+$/;
  if(inputtxt.value.match(letters)){
      return true;
  }else{
      alert('Please input letters only');
      return false;
  }
} 
<form action="#" id="form1" name="form1" method="post">
  <input name="Forename" type="text" required="required" id="Forename2" onclick="allLetter(document.form1.text)"/>
</form>

Upvotes: 1

Views: 8154

Answers (4)

Nina Scholz
Nina Scholz

Reputation: 386570

You could change the event to onkeyup, because with onclick the input has not taken place and the value could not be tested.

Then you need to hand over the element, the easiest is to use this as reference to the actual element.

For the search of not wanted character, you could check the whole string for the wanted characters.

function allLetter(inputtxt) {
    var letters = /^[a-z]*$/i;
    if (!inputtxt.value.match(letters)) {
        alert('Please input letters only');
    }
}
<form action="#" id="form1" name="form1" method="post">
  <input name="Forename" type="text" required="required" id="Forename2" onkeyup="allLetter(this)" />
</form>

Upvotes: 0

Matt
Matt

Reputation: 2290

why not just use a pattern input

<form action="#" id="form1" name="form1" method="post">
    <input name="Forename" type="text" required="required" id="Forename2" pattern="[A-Za-z]+" />
</form>

Upvotes: 4

Trevor
Trevor

Reputation: 2922

You can use the pattern to do what you want to do. https://www.w3schools.com/tags/att_input_pattern.asp

<form action="#" id="form1" name="form1" method="post">
    <input name="Forename" type="text" required="required" id="Forename2" pattern="^[A-Za-z]+$" />
</form>

But note that such code should be validated server side on submit. It's trivial to override html input patterns and javascript. So a server must validate all inputs on post.

You can try it out there https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_input_pattern

Upvotes: 0

M&#225;t&#233; Safranka
M&#225;t&#233; Safranka

Reputation: 4116

document.form1.text is not a valid way to access your text input field. document.forms[0].elements['Forename'] works. Try reading up on the document and the Form objects on MDN for more details.

Upvotes: 0

Related Questions