Using getters and setters for data that came from a form

function User(fullname,username,email,password,postcode,age,aggrement){
    this.fullname=fullname,
    this.username=username,
    this.email=email,
    this.password=password,
    this.postcode=postcode,
    this.age=age,
    this.aggrement=aggrement
}
Object.defineProperty(User.prototype,"fullname",{
    set: function(value){
        if(value.length<8){
            this.fullname="invalid"
        }else{
            this.fullname=value
        }
    }
})


function display(){
    event.preventDefault()
    const fullname=document.getElementById("fname").value
    const username=document.getElementById("username").value
    const email=document.getElementById("email").value
    const password=document.getElementById("password").value
    const postcode=document.getElementById("postCode").value
    const age=document.getElementsByName("age")[0]
    const aggrement=false
    let firstName=fullname.split(" ")[0]
    firstName= new User(fullname,username,email,password,postcode,age,aggrement)
    console.log(firstName)

  
}

I would like to get data from the form and create an object with that form while creating the object I would like to make some rules, such as the length of fullname should be longer than 8 etc. Can anyone tell me how i can use getters and setter ton this project?

I understand what you’re trying to do, but you’re overcomplicating things by using a setter. YMMV, but generally getters and setters aren’t really very useful in JS, they aren’t used very much.

HTML already provides validation that will do what you want it to do. This functionality can also be accessed/used via JS using the ConstraintValidation API. Also, the browser API includes a FormData object that does what your User class is trying to do initially (build an object from the values in a form).

This is detailed:

https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation

Note that you have a syntax error anyway – getters and setters can’t hold values, but you’ve given your setter function the same name as a property that does hold a value (fullname). You can’t call a getter/setter the same name as a property that holds a value: they’re a way of dynamically accessing/updating an actual concrete property.

Also, is there a reason why you aren’t using the class syntax? It’s a lot easier to read and write

1 Like

Thank you very much, I was just trying to practice getter setters with dom :slight_smile: