Reputation:
Back again with another absolute beginner question. I'm validating a form, and I want the text input to be limited to more than 2 and less than 15 characters. I have tried:
function validateForm(formElement) {
var valid = true;
if (formElement.first_name.value.length < 2) return focusElement(formElement.first_name, 'Please enter a First Name that is more than 2 characters long.');
if (formElement.first_name.value.length > 15) return focusElement(formElement.first_name, 'Please enter a First Name that is less than 15 characters long.');
As well as
if (formElement.first_name.value.length < 2 && formElement.first_name.value.length > 15) return focusElement(formElement.first_name, 'Please enter a First Name that is more than 2 and less than 15 characters long.');
Both resulting in errors. How can I accomplish this?
Upvotes: 1
Views: 9653
Reputation: 123
Which error did you get? I think FocusElement is your user-defined function. I test your code like following and it's ok.
<form name="frm">
<input type="text" name="first_name">
<input type="button" onClick="validateForm(frm)" value="Submit">
</form>
I use your validateForm function and write FocusElement javascript function as follow.
function focusElement(control,message)
{
control.focus();
alert(message);
}
And if you want to use second validation code, you should use || instead of &&.
Upvotes: 0
Reputation: 155
Your second validation code is incorrect.
Nothing could be <2 and at the same time >15.
You should use 'OR' ||
operation in between, NOT 'AND' &&
.
What is FocusElement
. Show the code.
Upvotes: 0
Reputation: 1233
There's a logic issue here - the length can't be less than 2 AND greater than 15. What you're should be using is less than 2 OR greater than 15:
if (formElement.first_name.value.length < 2 || formElement.first_name.value.length > 15) return focusElement(formElement.first_name, 'Please enter a First Name that is more than 2 and less than 15 characters long.');
I'm also not sure what you're using the valid = true
variable for here
Upvotes: 1