I am having a really hard time with a form validation and would appreciate some help.
(我在表单验证方面遇到了很多困难,希望能有所帮助。)
Essentially I have a form with various required fields, to include inputs, select, and textarea.(基本上,我有一个带有各种必填字段的表单,其中包括输入,选择和文本区域。)
One of the form fields is for an email address that I want to validate.(表单字段之一是我要验证的电子邮件地址。)
The problem I have is that I loop through the form elements using the querySelectorALL and check to see if a field is both required AND not empty.
(我遇到的问题是,我使用querySelectorALL遍历表单元素,并检查一个字段是否既是必需的又不是空的。)
The problem I have is integrating a second validation for the email field.(我遇到的问题是对电子邮件字段进行第二次验证。)
In the main loop, it may show as required and NOT empty, but could contain an invalid email value.(在主循环中,它可能显示为必填项,并且不为空,但可能包含无效的电子邮件值。)
So I thought to create a second conditional in the for loop, to check if the name of the item is "Email", and if it was, check it for validity.
(因此,我想在for循环中创建第二个条件,以检查项目名称是否为“ Email”,如果是,请检查其有效性。)
What I find is that submitting the form with the placeholder makes the field's placeholder text red.
(我发现,使用占位符提交表单会使该字段的占位符文本变为红色。)
If I then put in an invalid email address, the field turns black, but if you look at my conditional, if it is an invalid email the value should stay red, but it does not.(如果我随后输入了无效的电子邮件地址,则该字段将变为黑色,但如果您查看我的条件电子邮件,则该字段应为红色,但不是。)
I hope this is making sense.
(我希望这是有道理的。)
I have been at this for hours and really struggling.(我已经在这里呆了几个小时了,真的很挣扎。)
function validateAppt() { var returnVal = true; var divElem = document.getElementById("appointmentform"); var inputElements = divElem.querySelectorAll("input, select, textarea"); inputElements.forEach(a => a.style.color = "black"); inputElements.forEach(a => a.style.borderColor = "black"); for (let i = 0; i < inputElements.length; i++) { if (inputElements[i].required && inputElements[i].value == "") { inputElements[i].style.borderColor = "red"; if (inputElements[i].type != 'select-one') { inputElements[i].style.setProperty("--c", "red"); } else { inputElements[i].style.color = "red"; } returnVal = false; } if (inputElements[i].name == "Email") { if (!validateEmail(inputElements[i].value)) { inputElements[i].style.setProperty("--c", "red"); inputElements[i].style.color = "red"; console.log("InValid Email"); } else { inputElements[i].style.color = "black"; console.log("Valid Email"); } } } if (!returnVal) { $("#appointment_introduction").css('color', 'red').text('Please complete required form fields.'); $('html, body').animate({ scrollTop: $('#appointment_introduction').offset().top - 200 }, 2000); return false; } else { return true; } } function validateEmail(email) { var re = /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,10}|[0-9]{1,3})(\]?)$/; return re.test(email); }
ask by TMHDesign translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…