简体   繁体   English

检查输入是否以特定字符结尾

[英]check if input ends with specific character

I have this basic input field: 我有这个基本的输入字段:

<input type="text" name="one" />

How can I make sure user ends the input value with a specific character, for example comma (,) before running server-side code? 如何确保用户在运行服务器端代码之前以特定字符(例如,逗号)结束输入值?

Example: 例:

"hello world" (invalid) “ hello world”(无效)

"hello world," (valid) “ hello world”(有效)

You can use includes() 您可以使用include()

 var str = 'hello world,' if (str.includes(',',-1)) alert ('valid') 

Note that includes is an es6 feature and will only work in modern browsers, see the link I posted above for further information and a polyfill. 请注意,includes是es6功能,仅在现代浏览器中可用,请参阅我上面发布的链接以获取更多信息和polyfill。

This can be done using HTML5's input pattern attribute, which validates input with a regular expression. 这可以使用HTML5的输入pattern属性来完成,该属性使用正则表达式验证输入。 The form will not be allowed to submit in modern browsers that support this attribute - but you should always validate user input server-side as well. 不允许在支持该属性的现代浏览器中提交表单-但是您还应该始终在服务器端验证用户输入。

 input:valid { background: lime; } input:invalid { background: red; } 
 <input type="text" pattern="(.+?),$"> 

The CSS used in this example is purely to display when the input is valid (green). 本示例中使用的CSS仅在输入有效(绿色)时显示。

Why don't you just use HTML5 pattern validation? 您为什么不只使用HTML5模式验证? It's very easy and no Javascript to maintain. 这非常容易,无需维护Javascript。

Demo Snippet: 演示片段:

 <form> <input type="text" name="one" pattern=".*,$" /> <input type="submit" value="Submit" /> </form> 

HTML: HTML:

<form name="myForm">
  <input type="text" name="one" onkeypress="validateForm()">
  <input type="submit">
</form>

JS: JS:

function validateForm() {
    var x = document.forms["myForm"]["one"].value;
    if(x.charAt(x.length-1) == ','){
    console.log("true");
    }else{
   console.log("false");
    }
}

There javascript function endsWith which check is string ends with certain character 有javascript函数endsWith,其中检查字符串以某些字符结尾

 var chr  = "Hello world,";
    if(chr.endsWith(",") {

    }else{

    }

as kenny said it wont worked on IE..MDN has provided protoype function for this function 正如肯尼(Kenny)表示,不会在IE上工作。.MDN已为此功能提供了原型功能

if (!String.prototype.endsWith) {
  String.prototype.endsWith = function(searchString, position) {
      var subjectString = this.toString();
      if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) {
        position = subjectString.length;
      } 
      position -= searchString.length;
      var lastIndex = subjectString.indexOf(searchString, position);
      return lastIndex !== -1 && lastIndex === position;
  };
}

The most basic method is similar to Marcin C's: 最基本的方法类似于Marcin C:

function endsWith(str, end) {
    var $len = str.length,
    $endlen = end.length;
    if (substr($len - $endlen, $endlen) === end) {
        return true;
    } else {
        return false;
    }
}

I would add an ID, in order to easily extract the value: 我将添加一个ID,以便轻松提取值:

var textInputValue = document.getElementById("myIdHere").value; 

Then use regex to see if it matches your pattern: 然后使用正则表达式查看它是否与您的模式匹配:

if( textInputValue.match(/,$/) ){
     alert("the input is valid!");
} else {
     alert("sorry, invalid input"); 
}

Here is a fiddle: http://jsfiddle.net/ybsuyx6e/ 这是一个小提琴: http : //jsfiddle.net/ybsuyx6e/

/,$/.test("hello world,") // true

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

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