TransWikia.com

How do I use constraints for input validations using vanilla javascript?

Stack Overflow Asked by user9314692 on December 20, 2021

Assuming we are given the input

const username = "Bob"

I want to run it through a constraint

var constraints = {
    username: {
      required: true,
      minLength: 10,
      maxLength: 100,
      exclusions: {
          values: ["Bob", "Bobby"],
          message: "'%{value}' is not allowed"
      }
    },

  };

var messages: {
    required: "This field is required.",
    minLength:  "Please enter at least {0} characters." 
}

I want to make a function so that

validate({username: username}, constraints); => {username: ["Length must be at least 10 characters", "Bob is not allowed"]}

Unsure how to go about making this function

ATTEMPT

function validate(attributes, constraints) {
    const messages = []
    for (const property in attributes) {
        for (const constraint in constraints[property]) {
            const prop = constraints[property][constraint]
            if (constraint === "required" && attributes[property] === "") {
                messages.push("This field is required")
            } else if (constraint === "minLength" && attributes[property] < prop) {
                messages.push(`This field must be at least ${prop}`)
            } else if (constraint === "maxLength" && attributes[property] > prop) {
                messages.push(`This field must be at most ${prop}`)
            }
        }
    }
    console.log(messages)
    return messages

}

validate({ username: "" }, constraints)

Seems very messy

2 Answers

You could use the ValidityState interface if it's a simple form, or if you could use jQuery form validation plug-in Here is an example using ValidityState interface

var input=document.getElementById("input")
var constraints = {
    username: {
      required: true,
      minLength: 10,
      maxLength: 100,
      exclusions: {
          values: ["Bob", "Bobby"],
          message: "'%{value}' is not allowed"
      }
    },

  };

var messages= {
    required: "This field is required.",
    minLength:  "Please enter at least 5 characters." 
}
btn.addEventListener("click",()=>{
 var validityState_object = input.validity;
 if (validityState_object.valueMissing)
 {
  input.setCustomValidity(messages.required);
  input.reportValidity();
 }
 if (validityState_object.tooShort)
 {
  input.setCustomValidity(messages.minLength);
  input.reportValidity();
 }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="input" minlength="5" required="required">

<button id="btn">send</button>

Answered by Sven.hig on December 20, 2021

const constraints = {
  username: {
    required: true,
    minLength: 10,
    maxLength: 100,
    exclusions: {
        values: ["Bob", "Bobby"],
        message: "'%{value}' is not allowed"
    }
  }
}

function validate(string){
  if(string.length<constraints.username.minLength
    ||string.length>constraints.username.maxLength
    ||constraints.username.exclusions.values.includes(string)){
    return false;
  }
  return true;
}
console.log(validate("Bob"));
console.log(validate("Bobby"));
console.log(validate("Baa"));
console.log(validate("Bobsssssssss"));

Answered by luek baja on December 20, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP