skip to Main Content

can somebody help me with my error. Currently I’m building resident forms this page for Contact page. Now, I want to add validations in the contact fields I want if the resident selects mobile the mobile number should be start at 09. However, when residents select home there no validation regarding the format of number.

The Contact Type Values

1 for Mobile;
2 for Home

See the attached code.

The javascript for the validation of contact number is

function validateContactNumber

RegisterStepThree.cshtml

@model Registration
@{
    ViewData["Title"] = "Register Page - Step Three";
}
<div class="container mt-5">
    <div class="row">
        <div class="col-md-12">
            <h2 class="text-center mb-4">Contact Details</h2>
            <form asp-page-handler="RegisterStepThree" method="post">
                <div id="addressesContainer" class="row mt-3 fieldRow">
                    @for (int i = 0; i < 2; i++)
                    {
                        <div class="col-md-2 mb-3">
                            <label class="form-label">Contact type</label>
                            <select class="form-select contact-type" asp-for="Contacts[i].ContactType" onchange="validateContactType(this)" id="contactType@(i)">
                                <option value="">Select Contact Type</option>
                                @foreach (var type in ViewBag.ContactTypes.ContactTypes)
                                {
                                    <option value="@type.CODE_VALUE">@($" {type.Description}") Number</option>
                                }
                            </select>
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">Contact No</label>
                            <input type="text" class="form-control contact-field" asp-for="Contacts[i].ContactNumber" id="contactNumber@(i+1)" placeholder="Enter contact number" maxlength="11" oninput="validateContactNumber(this)">
                        </div>
                    }
                </div>
                <!-- Error message display area -->
                <div id="error-message" class="text-danger mb-3" style="display: none;"></div>
                <button type="submit" id="submit-button" class="btn btn-primary w-100" disabled>Next</button>
            </form>
        </div>
    </div>
</div>

@section Scripts {
    <script>
        function validateContactType(selectElement) {
            const contactTypeElements = document.querySelectorAll('.contact-type');
            const selectedValues = Array.from(contactTypeElements).map(el => el.value);
            const errorMessageElement = document.getElementById('error-message');

            const hasDuplicates = selectedValues.some((value, index) =>
                value && selectedValues.indexOf(value) !== index
            );

            if (hasDuplicates) {
                errorMessageElement.innerText = 'Contact type already selected';
                errorMessageElement.style.display = 'block';
                selectElement.value = ''; // Reset the current selection
            } else {
                errorMessageElement.style.display = 'none';
            }
            validateForm();
        }

        function validateContactNumber(inputElement) {
            const contactTypeElement = inputElement.closest('.fieldRow').querySelector('.contact-type');
            const errorMessageElement = document.getElementById('error-message');

            inputElement.value = inputElement.value.replace(/[^0-9]/g, '');

            if (contactTypeElement.value === '1') { // Assuming '1' is the value for "Mobile"
                if (!/^09d{9}$/.test(inputElement.value)) {
                    errorMessageElement.innerText = 'Please input a valid mobile number starting with 09';
                    errorMessageElement.style.display = 'block';
                    inputElement.setCustomValidity('Invalid mobile number');
                } else {
                    errorMessageElement.style.display = 'none';
                    inputElement.setCustomValidity('');
                }
            } else {
                inputElement.setCustomValidity('');
            }

            validateForm();
        }

        function validateForm() {
            const contactTypeElements = document.querySelectorAll('.contact-type');
            const contactFieldElements = document.querySelectorAll('.contact-field');
            const submitButton = document.getElementById('submit-button');
            const errorMessageElement = document.getElementById('error-message');

            let isValid = true;

            contactTypeElements.forEach(element => {
                if (element.value === '') {
                    isValid = false;
                }
            });

            contactFieldElements.forEach(element => {
                if (element.value === '' || !element.checkValidity()) {
                    isValid = false;
                }
            });

            if (isValid && errorMessageElement.style.display === 'none') {
                submitButton.disabled = false;
            } else {
                submitButton.disabled = true;
            }
        }

        const contactFields = document.querySelectorAll('.contact-field, .contact-type');
        contactFields.forEach(field => {
            field.addEventListener('input', validateForm);
        });

        document.addEventListener('DOMContentLoaded', validateForm);
    </script>
}

UI

2

Answers


  1. The reason why the validation is not working well is the selector is always the first select.

    The code const contactTypeElement = inputElement.closest('.fieldRow').querySelector('.contact-type'); the closest is the fieldRow div. Then querySelector will always select the first select.

    I suggest you could use the const contactTypeElement = inputElement.parentElement.previousElementSibling.querySelector('.contact-type'); instead.

    Besides, you also need make sure the ViewBag.ContactTypes‘s mobile type CODE_VALUE is 1.

    More details, you could refer to below codes:

        function validateContactNumber(inputElement) {
            const contactTypeElement = inputElement.parentElement.previousElementSibling.querySelector('.contact-type');
    
            
            const errorMessageElement = document.getElementById('error-message');
    
            inputElement.value = inputElement.value.replace(/[^0-9]/g, '');
           
            if (contactTypeElement.value === '1') { // Assuming '1' is the value for "Mobile"
                if (!/^09d{9}$/.test(inputElement.value)) {
                    errorMessageElement.innerText = 'Please input a valid mobile number starting with 09';
                    errorMessageElement.style.display = 'block';
                    inputElement.setCustomValidity('Invalid mobile number');
                } else {
                    errorMessageElement.style.display = 'none';
                    inputElement.setCustomValidity('');
                }
            } else {
                inputElement.setCustomValidity('');
            }
    
            validateForm();
        }
    
    Login or Signup to reply.
  2. const contactTypeElement = inputElement.closest('.fieldRow').querySelector('.contact-type');

    always selects the first "contact-type" element.

    you can wrap the entire elements inside for loop starting from <div class="col-md-2 mb-3"> with a div with class fieldRow and remove the fieldRow from <div id="addressesContainer" class="row mt-3 fieldRow">

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search