简体   繁体   English

输入框验证

[英]validation on input box

I want to create a Input Box for entering the private entering details of a person, On which first character has to be A or E and rest can be alphanumeric and no special character are allowed. 我想创建一个输入框,用于输入一个人的私人输入详细信息,其中第一个字符必须是A或E,​​其余可以是字母数字,不允许使用特殊字符。 I need to do validation for the same that no one enter any special character and First character has to be A or E (all has to be check on the client side) 我需要做同样的验证,没有人输入任何特殊字符,第一个字符必须是A或E(所有必须在客户端检查)

Can any one guide me how to proceed 任何人都可以指导我如何进行

Look in to regex with JavaScript, along with the keydown event. 使用JavaScript查看正则表达式以及keydown事件。 You can attach a function to the keydown event, and inside this function check the input box(es) match and then proceed as you wish. 您可以将函数附加到keydown事件,并在此函数内部检查输入框匹配,然后按照您的意愿继续。

Something like this: (not tested) 这样的事情:(未经测试)

<script>
function checkInput() {
  var inputToCheck = document.getElementById('my_input');
  if (!inputToCheck.value.match(/[AE]\w+/)) {
    // do something here, like alert them or remove special characters with .replace
  }
}
</script>

<input id="my_input" onkeydown="checkInput();" />

If this is the only field to validate I would write my own with js & regexp as Leonard Challis wrote (but on the keyup event). 如果这是唯一要验证的字段,我将使用js&regexp编写自己的字段,正如Leonard Challis写的那样(但是在keyup事件中)。

If there will be a lot of fields and perhaps multiple forms on the site, I would consider a framework. 如果网站上有很多字段和多个表单,我会考虑一个框架。 This is pretty good: http://bassistance.de/jquery-plugins/jquery-plugin-validation/ 这非常好: http//bassistance.de/jquery-plugins/jquery-plugin-validation/

If you would be using that one you could write a custom function for your special needs. 如果你要使用那个,你可以编写一个自定义功能,以满足您的特殊需求。 http://docs.jquery.com/Plugins/Validation/Validator/addMethod#namemethodmessage http://docs.jquery.com/Plugins/Validation/Validator/addMethod#namemethodmessage

This sounds like a homework assignment (since starting with specifically “E” or “A” sounds very artificial), so I'd suggest first deciding on the interpretation of the task. 这听起来像是一个家庭作业(因为从具体的“E”或“A”开始听起来非常人为),所以我建议首先决定对任务的解释。 Should “E” and “A” be interpreted case-insensitively? “E”和“A”应该不区分大小写吗? What exactly does “alphanumeric” mean? “字母数字”究竟是什么意思? For example, is “Σ” or “Я” or “١” alphanumeric? 例如,是“Σ”或“Я”或“1”字母数字? If the purpose is to do the checks client-side, should you try to make the page completely non-functional when JavaScript is disabled, or should you just do the checks client-side as far as possible ? 如果目的是做检查的客户端,你应该尽量使页面完全无功能,当JavaScript被禁用,或者你应该只是做了检查客户端尽可能 (In the latter case, consider using the pattern attribute in HTML. On some modern browsers, it causes the check to be performed even when JavaScript is disabled.) (在后一种情况下,请考虑在HTML中使用pattern属性。在某些现代浏览器中,即使禁用JavaScript,也会导致检查。)

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

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