gpt4 book ai didi

javascript - 我想在字段为空或输入错误字段时使用红色边框验证表单字段

转载 作者:行者123 更新时间:2023-11-28 06:35:50 27 4
gpt4 key购买 nike

我想在字段为空或用户输入错误字段时使用红色边框验证此表单。

我还想在字段无效时禁用提交按钮。

请注意,还有其他非必填字段,例如 MOBILE 和 EMAIL(它们可以稍后在“编辑用户详细信息”中提交)。尽管如果输入了错误的电子邮件,我也想对其进行验证。

<form  action="" method="POST">
<input type="date" name="date" placeholder="Registration Date" /></br>
<input name="full_names" type="text" placeholder="Full names" /></br>
<input name="mobile" type="text" placeholder="Mobile" /></br>
<span>Select status </span>
<select name="status">
<option value="Paid">Paid</option>
<option value="Unpaid">Unpaid</option>
</select></br>

<span>Select Chapter </span>
<select name="chapter">
<option value="Known">Known</option>
<option value="Unknown">Unknown</option>
</select></br>

<span>Select Gender </span>
<select name="gender">
<option value="Male">Male</option>
<option value="Female">Female</option>
</select></br>

<input type="text" name="email" placeholder="Email Address" /></br>

<textarea type="text" placeholder="Any Remarks" rows="2" name="remarks"></textarea></br>

<button type="submit">Submit </button>

</form>

最佳答案

HTML5 内置了很多这样的东西,包括 required 属性和提供正则表达式 pattern 属性以进行验证的能力。有些甚至是内置的,例如当您使用 type="email" 属性而不是 type="text" 时。

使用 HTML5 验证 + CSS3,您可以选择 :invalid 状态并将样式应用于该状态的元素。

虽然这不会将 disabled 状态应用于提交按钮,但如果验证失败,它不会提交表单。

input,
textarea {
margin: 5px 0;
padding: 5px 10px;
border: 1px solid #ccc;
border-radius: 5px;
}

input:invalid,
select:invalid,
textarea:invalid {
border-color: red;
}
<form action="" method="POST">
<input type="date" name="date" placeholder="Registration Date" required />
<br/>
<input name="full_names" type="text" placeholder="Full names" required />
<br/>
<input name="mobile" type="tel" pattern='[\+]\d{2}[\(]\d{2}[\)]\d{4}[\-]\d{4}' placeholder="Mobile" title="+99(99)9999-9999" />
<!-- Pattern from: http://www.htmlgoodies.com/html5/tutorials/whats-new-in-html5-forms-email-url-and-telephone-input-types.html#fbid=UQp7PiVwsX2 -->
<br/>
<span>Select status </span>
<select name="status" required>
<option value="Paid">Paid</option>
<option value="Unpaid">Unpaid</option>
</select>
<br/>

<span>Select Chapter </span>
<select name="chapter" required>
<option value="Known">Known</option>
<option value="Unknown">Unknown</option>
</select>
<br/>

<span>Select Gender </span>
<select name="gender" required>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
<br/>

<input type="email" name="email" placeholder="Email Address" />
<br/>

<textarea type="text" placeholder="Any Remarks" rows="2" name="remarks" required></textarea>
<br/>

<button type="submit">Submit</button>

</form>

关于javascript - 我想在字段为空或输入错误字段时使用红色边框验证表单字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34694686/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com