EndsWith在Javascript中用于验证表单

时间:2018-01-05 07:49:25

标签: javascript forms validation

我有一个问题。如何在javascript中执行验证表单,条件是"必须以' City'"?

结束

enter image description here

1 个答案:

答案 0 :(得分:0)

这是一个简单的例子,我必须让你了解endsWith()方法。



function myFunction2() {
    var str = "This is City but I am not there";
    var n = str.endsWith("City");
    document.getElementById("result").innerHTML = n;
}

function myFunction() {
    var str = "Welcome to my City";
    var n = str.endsWith("City");
    document.getElementById("result").innerHTML = n;
}

function validate(){
   var txtdata = document.getElementById("city").value;
   var txtdata = txtdata.endsWith("City");
   if(txtdata){
      document.getElementById("result2").innerHTML = "City Found at end";
   }else{
      document.getElementById("result2").innerHTML = "Must be ended with City";
   }
    
}

<button onclick="myFunction()">Check its working with City</button>

<button onclick="myFunction2()">Check its working without City</button>

<div id="result"></div>

<!-- Validate in form data -->
<form>
   <input type="text" id="city" name="city"/>
<input type="button" onclick="validate()" value="Submit"/>
</form>

<div id="result2"></div>
&#13;
&#13;
&#13;

以类似的方式,您必须从表单存储输入它在变量do validation中。