0

So basically I have created input fields in HTML for a persons first and last names. I want this field to limit their inputs to only text and give them an alert otherwise using vanilla JS please.

Here is the HTML code:

<div>
        First Name:<br> <input id="name" type="text" placeholder="Type Here" pattern="[A-Za-z]"><br>
        Last Name:<br> <input id="name" type="text" placeholder="Type Here" pattern="[A-Za-z]">
</div>

As you can see I previously tried to limit the input by using the pattern="" method I saw in another post but couldn't get it to work. Advice on that would be much appreciated as well.

And here is my JS function as it stands now:

var nameinput=document.getElementById('name').value;
var input=function(field){
    if(isNaN(field)===false || field===""){
        alert('Please Enter Your Name');
        return false;


    }
}
input(nameinput)

It's probably something obvious. I'm pretty new to JS but any help would be greatly appreciated!

2
  • the pattern attribute works on form + submit I think. Commented Jul 27, 2015 at 23:26
  • Your pattern regex only accepts one character, change to [a-zA-Z]+ to allow one or more, remember that pattern attribute is not supported on all browsers, Safari does not support it. Commented Jul 27, 2015 at 23:35

1 Answer 1

1

If you want it to check all the time, try to implement a custom onChange callback i.e. <input type="text" name="firstName" onChange="verif()">, or, if you want it to verify only at submit time, add onSubmit="verif()" to your form. For both case the verif() function looks like

function verif(){
  var firstName = document.getElementByName("firstName")[0].value;
  if(!firstName.match(/[\A-Za-z]+/i)) {
    alert("You can only enter characters");// Or whatever message
    document.getElementByName("firstName")[0].focus();
  }
  var lastName = document.getElementByName("lastName")[0].value;
  if(!lastName.match(/[\A-Za-z]+/i)) {
    alert("You can only enter characters");// Or whatever message
    document.getElementByName("lastName")[0].focus();
  }
}

By the way, this code assume that you use the name property with your inputs, which you should alway use with inputs. You also shouldn't use two time the same id.

Sign up to request clarification or add additional context in comments.

Comments

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.