Reputation: 483
Hi I'm new to javascript and I have the following function:
function checkform() {
var theForm = document.getElementById('login_form');
var regName = /^[a-zA-Z ]+$/;
var firstname = theForm.firstname.value;
if (
(firstname == "" || theForm.firstname.value.length > 30 ) &&
(regName.test(firstName) == false)
) {
alert("That is not a valid first name!");
theForm.firstname.focus();
return false;
}
}
It works in the sense that it checks that the data is not empty and not greater than 30. My problem is that is currently allows the user to enter data that does not match my regex i.e. numerical data. I can not see any problems with the logic.
Thanks
Upvotes: 0
Views: 364
Reputation: 4047
In your conditional statement try doing this:
if ((firstname == "" || theForm.firstname.value.length > 30 ) || (regName.test(firstname) == false)) {
// ...
}
I've changed the "&&" (and) operator to "||" (or), because you don't need to check against both conditions (empty or longer than 30 AND not matching regexp), but just any of them (empty or longer than 30 or not mathing regexp).
Upvotes: 3
Reputation: 546
<input id="txtChar" onkeypress="return isNumberKey(event)"
type="text" name="txtChar">
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57) || event.value > 30)
return false;
return true;
}
Upvotes: 0
Reputation: 2970
Try it
var regName = /^[a-zA-Z ]{3,30}$/;
if (!regName.test(firstName)){ //make an error
Upvotes: 1