Reputation: 109
I cannot seem to figure out how to get this script to validate that only letters are being entered. So if a number is entered, then an error should be returned.
HTML
<form name="myForm" action="demo_form.asp"
onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
Javascipt
<script>
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == null || x == "") {
alert("First name must be filled out");
return false;
}
}
</script>
Upvotes: 1
Views: 580
Reputation: 26444
This might be best done with HTML5's new pattern
attribute. However, it doesn't work in Safari or in Internet Explorer 9-.
From the Mozilla Developer Network
A regular expression that the control's value is checked against. The pattern must match the entire value, not just some subset. Use the title attribute to describe the pattern to help the user. This attribute applies when the value of the type attribute is text, search, tel, url, email or password; otherwise it is ignored. The regular expression language is the same as JavaScript's. The pattern is not surrounded by forward slashes.
<form action="demo_form.asp">
Username: <input type="text" name="username"
pattern="[A-Za-z]+" title="Your username">
<input type="submit">
</form>
For browsers from the stone age, just use regex.
if (!/^[a-z]+$/i).test(exp)) {
return false;
}
Explanation
The ^
and $
characters signal that the string should both start and end with a letter
The +
modifier indicates that we're searching for one or more such letters.
Finally, the case-insensitive flag i
is raised to indicate it can be upper or lower case.
Upvotes: 6