简体   繁体   中英

How to validate greater than, less than in Javascript?

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?

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

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.

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 &&.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM