skip to Main Content

In my form validation I am try to check for empty strings, which will display one error message, then check that the length is no more than 15 character, which should display a different message. The problem is, the way I have it written, it is only check the length. If I remove it, the empty string check works. It seems it is only check the last thing in my statement. How can I rewrite thig to work for both items?

I tried both this:

const validate = (fieldValues = values) => {
    const temp = { ...errors };
    if ('name' in fieldValues)
        { temp.name = fieldValues.name ? '' : 'Location Name is required.'; }
        { temp.name = fieldValues.name.length < 16 ? '' : 'Location Name limited to 15 Characters.'; } 
    setErrors({
        ...temp
    });
    if (fieldValues === values)
        { return Object.values(temp).every(x => x === ''); }
};

And this:

const validate = (fieldValues = values) => {
    const temp = { ...errors };
    if ('name' in fieldValues)
        { temp.name = fieldValues.name ? '' : 'Location Name is required.'; }
    if ('name' in fieldValues)
        { temp.name = fieldValues.name.length < 16 ? '' : 'Location Name limited to 15 Characters.'; }
    setErrors({
        ...temp
    });
    if (fieldValues === values)
        { return Object.values(temp).every(x => x === ''); }
};

Both did the same thing.

adding pipes between just caused an error

3

Answers


  1. Here’s an example of a simple form validation function in JavaScript that checks for empty strings and strings with more than 15 characters:

    This function assumes that there is an HTML input element with the id "myInput" and an HTML element with the id "error" to display the error messages.

    The function first gets the input value and trims any whitespace from the beginning and end. If the input is empty, it sets the error message to "Please enter a value" and returns false, indicating that validation failed.

    If the input is not empty, it checks if the length of the input is greater than 15. If it is, it sets the error message to "The input must be 15 characters or less" and returns false.

    If validation is successful, the function clears the error message and returns true, indicating that validation passed.

    function validateForm() {
      // get the input value from the HTML input element
      var input = document.getElementById("myInput").value;
    
      // get the HTML element to display error messages
      var errorElement = document.getElementById("error");
    
      // check if input is empty or only contains whitespace
      if (input.trim() === "") {
        // if input is empty, set error message and return false
        errorElement.innerHTML = "Please enter a value";
        return false;
      } else if (input.length > 15) {
        // if input is longer than 15 characters, set error message and return false
        errorElement.innerHTML = "The input must be 15 characters or less";
        return false;
      }
    
      // if validation is successful, clear the error message and return true
      errorElement.innerHTML = "";
      return true;
    }
    
    Login or Signup to reply.
  2. First of all, the if statements in the second snippet can be simplified a bit:

    if ('name' in fieldValues) {
        temp.name = fieldValues.name ? '' : 'Location Name is required.';
        temp.name = fieldValues.name.length < 16 ? '' : 'Location Name limited to 15 Characters.';
    }
    

    Now let’s step through that code, assuming fieldValues.name is an empty string:

    1. if ('name' in fieldValues)' {...

    fieldValues.name is an empty string, but is still present, so 'name' in fieldValues is true. That means we’ll execute the code in the if statement.

    1. temp.name = fieldValues.name ? '' : 'Location Name is required.';

    fieldValues.name is '' (empty string), which evaluates to false in JavaScript. So now temp.name is 'Location Name is required.'. Great!

    1. temp.name = fieldValues.name.length < 16 ? '' : 'Location Name limited to 15 Characters.';

    fieldValues.name.length is zero, which is less than 16. So now you overwrite the previous error and temp.name is now ''.

    A better implementation would look like:

    if ('name' in fieldValues) {
      // Check fieldValues.name is null or empty
      if (!fieldValues.name) {
        temp.name = 'Location Name is required.';
      }
      // Check if length of string is too long
      else if(fieldValues.name.length > 15) {
        temp.name = 'Location Name limited to 15 Characters.';
      }
    }
    ...
    
    Login or Signup to reply.
  3. An alternative to using JavaScript to deal with the validation is to use the built-in browser form validation. Set the input as required, and then use input attributes like pattern to add input boundaries. Then have form notify the user when it’s submitted if those boundaries are violated.

    In this example the browser adds a pattern to the input to ensure that at least one character is entered, and less than fifteen are entered. Try clicking the button without entering anything in the input. A validation popup appears telling you to fill in the field. Adding more that fifteen characters will reveal a differently worded popup.

    Aside: you could also add maxlength and size to inhibit the visual boundaries of the input field, and ARIA descriptions to make the form more accessible.

    const { useState } = React;
    
    function Example() {
    
      const [ input, setInput ] = useState('');
    
      function handleChange(e) {
        setInput(e.target.value);
      }
    
      function handleSubmit(e) {
        e.preventDefault();
        console.log(`State: ${input}`);
      }
    
      return (
        <section>
          <form onSubmit={handleSubmit}>
            <label for="text">Enter text</label>
            <input
              required
              id="text"
              type="text"
              aria-describedby="textHint"
              placeholder="1-15 characters"
              // maxlength="15"
              // size="15"
              pattern="^.{1,15}$"
              value={input}
              onChange={handleChange}
            />
            <span class="hint" id="textHint">
              Enter text between 1 and 15 characters in length.
            </span>
            <button type="submit">Submit</button>
          </form>
        </section>
      );
    
    }
    
    ReactDOM.render(
      <Example />,
      document.getElementById('react')
    );
    * { font-size: 1.1rem; }
    input { margin: 0 0.25rem; }
    input:valid { border: 1px solid green; outline: none;}
    input:invalid { border: 1px solid red; outline: none; }
    .hint { margin-top: 0.25rem; font-size: 0.9rem; display: block; color: darkblue; }
    button { margin-top: 0.25rem; display: block; }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
    <div id="react"></div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search