javascriptmodel-view-controllerjavascriptmvc

Where do i have to put my form checking data method? View, Model or Controller


I have a basic form checking data method:

Do I have to put this method, in the view, model or controller.

checkFormData() {

    const nameField = this.form.elements.name;
    const firstNameField = this.form.elements.firstName;
    const mailField = this.form.elements.mail;
    const messageField = this.form.elements.message;
    const mailformat = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
    const dataFields = {};

    if (nameField.value.length < 2 || nameField.value.length > 25) {
        dataFields.name = false;
    } else {
        dataFields.name = true;
    }

    if (firstNameField.value.length < 2 || firstNameField.value.length > 25) {
        dataFields.firstName = false;
    } else {
        dataFields.firstName = true;
    }

    if (!mailField.value.match(mailformat)) {
        dataFields.mail = false;
    } else {
        dataFields.mail = true;
    }

    if (messageField.value.length < 2 || messageField.value.length > 500) {
        dataFields.message = false;
    } else {
        dataFields.message = true;
    }

    return dataFields;
}

Solution

  • you can keep it in the view part but in-case, if someone tries to hit the url (api) using postman or something like that, you have to write the validation logic in the controller as well, just to be sure.