简体   繁体   English

我需要JavaScript表单验证吗?

[英]Do I need JavaScript Form validation?

I'm working on some forms for a Website. 我正在为网站设计某些表格。 Currently I have the usual HTML Browser check (with "required"-tag and patterns and stuff in the inputs), I check the values in a JavaScript before submitting and I do a server-sided check of the data after submitting. 目前,我具有常规的HTML浏览器检查功能(在输入中带有“ required”标记以及模式和内容),在提交之前检查JavaScript中的值,并在提交之后在服务器端检查数据。

Everything works fine, even if I have only one of them enabled, but it seems a little bit overkill to me, so my question is if I can just leave the Javascript check out? 即使我只启用了其中一个,一切也都可以正常工作,但是对我来说似乎有点过大了,所以我的问题是我是否可以只退出Javascript? Of course I need to keep the server chek :D 当然,我需要保持服务器che:D

Looking forward to your answers! 期待您的回答!

You must always validate input at serverside. 您必须始终在服务器端验证输入。 Javascript is optional and it just to make life of your users easier. Javascript是可选的,它只是为了简化用户的生活。 Your users get better experience. 您的用户获得更好的体验。 That's it. 而已。

All modern browsers support the HTML5 form field attributes. 所有现代浏览器都支持HTML5表单字段属性。 As you are using those, you may skip the JS validation. 在使用这些代码时,您可以跳过JS验证。

To expand a little on the current answers: 为了扩大当前答案:

Server side validation is always required, you mentioned that. 您提到过,始终需要服务器端验证。

HTML and Javascript validation are used for different things. HTML和Java验证用于不同的事物。

The HTML required tag can be used to check a form's fields are not blank before a form submission. HTML必需标记可用于在提交表单之前检查表单的字段是否为空。

Javascript validation allows you to be far more flexible with what you want to validate and when . JavaScript验证可以让你远与要验证和什么 时候更灵活。 However, it requires more work because it's not as simple as a required tag. 但是,由于它不像必需的标签那么简单,因此需要更多的工作。

With Javascript you can do far more. 使用Javascript,您可以做更多的事情。 Some examples: 一些例子:

  • Validation that occurs as soon as a user starts to type 用户开始输入后立即进行的验证
  • Have the box highlight a different colour 让盒子突出显示不同的颜色
  • Show an error message 显示错误讯息
  • Have a big red cross appear next to invalid fields or a big green one next to valid ones 在无效字段旁边显示一个大的红色叉号,在有效字段旁边显示一个大的绿色叉号
  • Spin your page around when the user enters something invalid. 用户输入无效内容时旋转页面。 (don't actually do that) (实际上不这样做)
  • etc. 等等

Also note browser support for the required tag. 还要注意浏览器对必需标记的支持

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM